diff --git a/hack/pssaas-request-curl.sh b/hack/pssaas-request-curl.sh new file mode 100755 index 0000000..f6681a2 --- /dev/null +++ b/hack/pssaas-request-curl.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +curl -H 'Content-Type: application/json' -d '@sample-pssaas.json' localhost:8080/api/v1a/Scan/PSSaaS/run -vv | jq +#curl -H 'Content-Type: application/json' -d '@sample-pssaas-bad.json' localhost:8080/api/v1a/Scan/PSSaaS -vv diff --git a/hack/sample-pssaas-bad.json b/hack/sample-pssaas-bad.json new file mode 100644 index 0000000..77baf4e --- /dev/null +++ b/hack/sample-pssaas-bad.json @@ -0,0 +1,13 @@ +{ + "product-id": "jochrist-dev-test-rhbq", + "is-managed-service": false, + "cpaas-version": "latest", + "component-list":[ + {"build-id":"ASLKGOMQVVAAA", + "type":"pnc"}, + {"build-id":"ASLMBTBCNVAAA", + "type":"pnc"}, + {"foo":"bar"}], + "some-other-list":[{"this":"shouldn't work"}] +} + diff --git a/hack/sample-pssaas.json b/hack/sample-pssaas.json new file mode 100644 index 0000000..63cb3ce --- /dev/null +++ b/hack/sample-pssaas.json @@ -0,0 +1,15 @@ +{ + "product-id": "jochrist-dev-test-rhbq", + "is-managed-service": false, + "cpaas-version": "latest", + "component-list":[ + {"build-id":"ASLKGOMQVVAAA", + "type":"pnc"}, + {"build-id":"ASLMBTBCNVAAA", + "type":"pnc"}, + {"type":"git", + "repo":"https://code.engineering.redhat.com/gerrit/quarkusio/quarkus.git", + "ref":"2.13.8.Final-redhat-00001"} + ] +} + diff --git a/hack/single-brew-scan-stage.sh b/hack/single-brew-scan-stage.sh new file mode 100755 index 0000000..0622bdd --- /dev/null +++ b/hack/single-brew-scan-stage.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +curl --get \ + --data-urlencode "brewId=xterm-366-8.el9" \ + https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/single/brew -vv + +curl --get https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/2 -vv +curl --get https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/2/run -vv + diff --git a/hack/single-brew-scan.sh b/hack/single-brew-scan.sh new file mode 100755 index 0000000..513a4da --- /dev/null +++ b/hack/single-brew-scan.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +curl --get \ + --data-urlencode "brewId=xterm-366-8.el9" \ + localhost:8080/api/v1a/Scan/single/brew -vv + +curl --get localhost:8080/api/v1a/Scan/2 -vv +curl --get localhost:8080/api/v1a/Scan/2/run -vv + diff --git a/hack/single-git-scan-stage.sh b/hack/single-git-scan-stage.sh new file mode 100755 index 0000000..d82777f --- /dev/null +++ b/hack/single-git-scan-stage.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +curl --get \ + --data-urlencode "repo=https://code.engineering.redhat.com/gerrit/quarkusio/quarkus.git" \ + --data-urlencode "ref=2.13.8.Final-redhat-00001" \ + https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/single/git -vv + +curl --get https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/1 -vv +curl --get https://osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com/api/v1a/Scan/1/run -vv + diff --git a/hack/single-git-scan.sh b/hack/single-git-scan.sh new file mode 100755 index 0000000..9107fe1 --- /dev/null +++ b/hack/single-git-scan.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +curl --get \ + --data-urlencode "repo=https://code.engineering.redhat.com/gerrit/quarkusio/quarkus.git" \ + --data-urlencode "ref=2.13.8.Final-redhat-00001" \ + localhost:8080/api/v1a/Scan/single/git -vv + +curl --get localhost:8080/api/v1a/Scan/1 -vv +curl --get localhost:8080/api/v1a/Scan/1/run -vv + diff --git a/k8s/stage/app/service-account.yaml b/k8s/stage/app/service-account.yaml index 84ffcac..89bed26 100644 --- a/k8s/stage/app/service-account.yaml +++ b/k8s/stage/app/service-account.yaml @@ -2,11 +2,11 @@ apiVersion: v1 kind: ServiceAccount metadata: labels: - app.kubernetes.io/name: osh + app.kubernetes.io/name: osh-wrapper-client-sa app.kubernetes.io/version: 1.0.0-SNAPSHOT app.openshift.io/runtime: quarkus env: stage - name: osh + name: osh-wrapper-client-sa namespace: pct-security-tooling imagePullSecrets: - name: pct-security-osh-wrapper-client-pull-secret diff --git a/k8s/stage/app/tekton-rbac.yaml b/k8s/stage/app/tekton-rbac.yaml index e989543..a6d90a7 100644 --- a/k8s/stage/app/tekton-rbac.yaml +++ b/k8s/stage/app/tekton-rbac.yaml @@ -28,4 +28,4 @@ roleRef: name: osh-wrapper-tekton subjects: - kind: ServiceAccount - name: osh + name: osh-wrapper-client-sa diff --git a/mvnw b/mvnw deleted file mode 100755 index 41c0f0c..0000000 --- a/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index 8611571..0000000 --- a/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index 8bdcc04..a9acab6 100644 --- a/pom.xml +++ b/pom.xml @@ -1,27 +1,20 @@ - - - jboss - JBoss repository - http://repository.jboss.org/maven2 - - 4.0.0 - com.redhat.pctOshWrapper - osh + com.redhat.pctsec + osh-wrapper-service 1.0.0-SNAPSHOT - 3.10.1 + 3.11.0 17 UTF-8 UTF-8 quarkus-bom io.quarkus.platform - 2.16.6.Final + 3.1.2.Final true - 3.0.0-M7 + 3.0.0 @@ -38,119 +31,88 @@ io.quarkiverse.kerberos quarkus-kerberos - 1.0.0 + 2.1.0 io.quarkus - quarkus-openshift + quarkus-resteasy-reactive - org.json - json - 20220320 + io.quarkus + quarkus-openshift - + io.quarkiverse.tektonclient quarkus-tekton-client 1.0.1 - - io.quarkus - quarkus-resteasy-reactive - io.quarkus quarkus-arc io.quarkus - quarkus-junit5 - test + quarkus-hibernate-validator - io.rest-assured - rest-assured - test - - - - - jakarta.ws.rs - jakarta.ws.rs-api - 3.1.0 - - - - org.apache.commons - commons-lang3 - 3.12.0 - - - - org.postgresql - postgresql - 42.6.0 - - - - - org.hibernate - hibernate-core + io.quarkus + quarkus-resteasy-reactive-jackson - org.glassfish.jaxb - jaxb-runtime + org.apache.commons + commons-lang3 - io.quarkus quarkus-jdbc-postgresql - io.quarkus - quarkus-resteasy-reactive-jackson + quarkus-hibernate-orm-panache io.quarkus - quarkus-agroal + quarkus-smallrye-openapi - org.projectlombok - lombok - 1.18.26 - provided + info.picocli + picocli + 4.7.4 - - - javax.validation - validation-api - 1.0.0.GA + io.quarkus + quarkus-vertx - - jakarta.persistence - jakarta.persistence-api - 3.1.0 + io.quarkus + quarkus-kubernetes-config - - - org.eclipse.microprofile.rest.client - microprofile-rest-client-api - 3.0.1 + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test - + + io.smallrye + jandex-maven-plugin + 3.1.1 + + + make-index + + jandex + + + + ${quarkus.platform.group-id} quarkus-maven-plugin @@ -204,19 +166,6 @@ - - io.smallrye - jandex-maven-plugin - 3.1.1 - - - make-index - - jandex - - - - diff --git a/src/main/docker/Dockerfile.jvm b/src/main/docker/Dockerfile.jvm index 5ba77be..05a83fd 100644 --- a/src/main/docker/Dockerfile.jvm +++ b/src/main/docker/Dockerfile.jvm @@ -7,18 +7,20 @@ # # Then, build the image with: # -# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/rest-json-quickstart-jvm . +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/osh-wrapper-service-jvm . # # Then run the container using: # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart-jvm +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service-jvm # # If you want to include the debug port into your docker image -# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. +# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 +# when running the container # # Then run the container using : # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart-jvm +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service-jvm # # This image uses the `run-java.sh` script to run the application. # This scripts computes the command line to execute your Java application, and @@ -75,7 +77,7 @@ # accessed directly. (example: "foo.example.com,bar.example.com") # ### -FROM registry.access.redhat.com/ubi8/openjdk-17:1.14 +FROM registry.access.redhat.com/ubi8/openjdk-17:1.15 ENV LANGUAGE='en_US:en' @@ -86,7 +88,6 @@ COPY --chown=185 target/quarkus-app/*.jar /deployments/ COPY --chown=185 target/quarkus-app/app/ /deployments/app/ COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ - EXPOSE 8080 USER 185 ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" diff --git a/src/main/docker/Dockerfile.legacy-jar b/src/main/docker/Dockerfile.legacy-jar index 0e25744..7a8bbfd 100644 --- a/src/main/docker/Dockerfile.legacy-jar +++ b/src/main/docker/Dockerfile.legacy-jar @@ -7,18 +7,20 @@ # # Then, build the image with: # -# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/rest-json-quickstart-legacy-jar . +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/osh-wrapper-service-legacy-jar . # # Then run the container using: # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart-legacy-jar +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service-legacy-jar # # If you want to include the debug port into your docker image -# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. +# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 +# when running the container # # Then run the container using : # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart-legacy-jar +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service-legacy-jar # # This image uses the `run-java.sh` script to run the application. # This scripts computes the command line to execute your Java application, and @@ -75,7 +77,7 @@ # accessed directly. (example: "foo.example.com,bar.example.com") # ### -FROM registry.access.redhat.com/ubi8/openjdk-17:1.14 +FROM registry.access.redhat.com/ubi8/openjdk-17:1.15 ENV LANGUAGE='en_US:en' diff --git a/src/main/docker/Dockerfile.native b/src/main/docker/Dockerfile.native index 27a8aab..abab985 100644 --- a/src/main/docker/Dockerfile.native +++ b/src/main/docker/Dockerfile.native @@ -7,11 +7,11 @@ # # Then, build the image with: # -# docker build -f src/main/docker/Dockerfile.native -t quarkus/rest-json-quickstart . +# docker build -f src/main/docker/Dockerfile.native -t quarkus/osh-wrapper-service . # # Then run the container using: # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service # ### FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6 diff --git a/src/main/docker/Dockerfile.native-micro b/src/main/docker/Dockerfile.native-micro index 0289e20..504e8c5 100644 --- a/src/main/docker/Dockerfile.native-micro +++ b/src/main/docker/Dockerfile.native-micro @@ -10,11 +10,11 @@ # # Then, build the image with: # -# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/rest-json-quickstart . +# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/osh-wrapper-service . # # Then run the container using: # -# docker run -i --rm -p 8080:8080 quarkus/rest-json-quickstart +# docker run -i --rm -p 8080:8080 quarkus/osh-wrapper-service # ### FROM quay.io/quarkus/quarkus-micro-image:2.0 diff --git a/src/main/java/com/redhat/pctsec/model/BrewBuild.java b/src/main/java/com/redhat/pctsec/model/BrewBuild.java new file mode 100644 index 0000000..1a736f2 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/BrewBuild.java @@ -0,0 +1,37 @@ +package com.redhat.pctsec.model; + +import jakarta.persistence.Entity; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import java.net.URI; +import java.net.URL; + + +@Entity +public class BrewBuild extends BuildType { + + public BrewBuild(String buildRef) { + super(buildRef); + } + + public BrewBuild() { + super(); + } + + @Override + public URI SCMURL() { + return null; + } + + @Override + public URL URL() { + return null; + } + + @Override + public String revision() { + return null; + } + + +} diff --git a/src/main/java/com/redhat/pctsec/model/BuildType.java b/src/main/java/com/redhat/pctsec/model/BuildType.java new file mode 100644 index 0000000..7714f97 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/BuildType.java @@ -0,0 +1,35 @@ +package com.redhat.pctsec.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.persistence.*; + +import java.net.URI; +import java.net.URL; +import java.util.UUID; + +@Entity +@DiscriminatorColumn(name="REF_TYPE") +abstract public class BuildType { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private UUID id; + + @JsonProperty() + @Column(name="buildref") + public String buildRef; + + public BuildType(String buildRef) + { + this.buildRef = buildRef; + } + + public BuildType() { + + } + + //This is the git URL of the sources + abstract public URI SCMURL(); + //This is the URL of the build + abstract public URL URL(); + abstract public String revision(); +} diff --git a/src/main/java/com/redhat/pctsec/model/Git.java b/src/main/java/com/redhat/pctsec/model/Git.java new file mode 100644 index 0000000..f91eac1 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/Git.java @@ -0,0 +1,29 @@ +package com.redhat.pctsec.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import java.net.URI; +import java.util.UUID; + +@Entity +public class Git { + public Git() { + super(); + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private UUID id; + + public URI repo; + public String ref; + + public Git(String repo, String ref) { + this.repo = URI.create(repo); + this.ref = ref; + } +} diff --git a/src/main/java/com/redhat/pctsec/model/PNCBuild.java b/src/main/java/com/redhat/pctsec/model/PNCBuild.java new file mode 100644 index 0000000..36f9b55 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/PNCBuild.java @@ -0,0 +1,39 @@ +package com.redhat.pctsec.model; + +import jakarta.persistence.Entity; + +import java.net.URI; +import java.net.URL; + +@Entity +public class PNCBuild extends BuildType{ + public PNCBuild() { + super(); + } + + public PNCBuild(String buildRef) { + super(buildRef); + } + + @Override + public URI SCMURL() { + return null; + } + + @Override + public URL URL() { + return null; + } + + @Override + public String revision() { + return null; + } + + public static boolean isValidRef(String ref){ + //New type PNC Ref + if(ref.length()!=14) + return false; + return true; + } +} diff --git a/src/main/java/com/redhat/pctsec/model/RequestType.java b/src/main/java/com/redhat/pctsec/model/RequestType.java new file mode 100644 index 0000000..a589a78 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/RequestType.java @@ -0,0 +1,3 @@ +package com.redhat.pctsec.model; + +public enum RequestType {BREW, PNC, GIT} diff --git a/src/main/java/com/redhat/pctsec/model/Scan.java b/src/main/java/com/redhat/pctsec/model/Scan.java new file mode 100644 index 0000000..a1e3daa --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/Scan.java @@ -0,0 +1,116 @@ +package com.redhat.pctsec.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.transaction.Transactional; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.Instant; +import java.util.UUID; + +enum ScanState { + CREATED, TRIGGERED, RUNNING, SUCCESS, FAIL; +} +@Entity +public class Scan { + + public Scan() { + this.scanRequests = new ScanRequests(); + } + + public Instant getCreationTimestamp() { + return creationTimestamp; + } + + public void setCreationTimestamp(Instant creationTimestamp) { + this.creationTimestamp = creationTimestamp; + } + + public ScanState getState() { + return state; + } + + public void setState(ScanState state) { + this.state = state; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getRequestor() { + return requestor; + } + + public void setRequestor(String requestor) { + this.requestor = requestor; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + + public ScanRequests getScanRequests() { + return scanRequests; + } + + public void setScanRequests(ScanRequests scanRequests) { + this.scanRequests = scanRequests; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + public UUID id; + + + /* + @OneToOne + @NotNull + @JoinColumn(name = "product_id", referencedColumnName = "id") + private String productName; + */ + @Column(name="proudct_name") + private String productName; + + //@Temporal(TemporalType.TIMESTAMP) + + @CreationTimestamp + @JsonIgnore + @Column(name="creation_timestamp") + //@NotNull + private Instant creationTimestamp; + + @UpdateTimestamp + @JsonIgnore + @Column(name="update_timestamp") + //@NotNull + private Instant updateTimestamp; + + @Column(name="state") + @Enumerated(EnumType.STRING) + private ScanState state; + + @Column(name="requestor") + @NotNull + private String requestor; + + @Column(name="report_email") + @Email + private String email; + + @OneToOne(cascade = CascadeType.ALL, fetch=FetchType.LAZY) + @JoinColumn(name = "scan_requests_id", referencedColumnName = "id") + public ScanRequests scanRequests; +} diff --git a/src/main/java/com/redhat/pctsec/model/ScanRequest.java b/src/main/java/com/redhat/pctsec/model/ScanRequest.java new file mode 100644 index 0000000..2955d87 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/ScanRequest.java @@ -0,0 +1,110 @@ +package com.redhat.pctsec.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.redhat.pctsec.model.api.request.git; +import com.redhat.pctsec.tekton.brewTaskRun; +import com.redhat.pctsec.tekton.scmUrlPipelineRun; +import io.vertx.mutiny.core.eventbus.EventBus; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import jakarta.persistence.*; + +import java.util.HashMap; +import java.util.UUID; + +@ApplicationScoped +@Entity +public class ScanRequest { + + @Id + @GeneratedValue + protected UUID id; + private String metadata; + private String oshScanOptions; + + public EventBus getBus() { + return bus; + } + + public void setBus(EventBus bus) { + this.bus = bus; + } + + @Transient + @JsonIgnore + @Inject + EventBus bus; + + public RequestType getType() { + return type; + } + + private RequestType type; + + @OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "brew_build_id", referencedColumnName = "id") + @JsonInclude(JsonInclude.Include.NON_NULL) + public BrewBuild brewBuild; + + @OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "pnc_build_id", referencedColumnName = "id") + @JsonInclude(JsonInclude.Include.NON_NULL) + public PNCBuild pncBuild; + + @OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL) + @JoinColumn(name = "git_id", referencedColumnName = "id") + @JsonInclude(JsonInclude.Include.NON_NULL) + public Git git; + + public String getOshScanOptions() { + return oshScanOptions; + } + + public void setOshScanOptions(String oshScanOptions) { + this.oshScanOptions = oshScanOptions; + } + + public String getScanProperties() { + return scanProperties; + } + + public void setScanProperties(String scanProperties) { + this.scanProperties = scanProperties; + } + + @Column(name="scan_properties") + public String scanProperties; + public ScanRequest() { + } + + public ScanRequest(BrewBuild brewBuild) + { + this.type = RequestType.BREW; + this.brewBuild = brewBuild; + } + + public ScanRequest(PNCBuild pncBuild) + { + this.type = RequestType.PNC; + this.pncBuild = pncBuild; + } + + public ScanRequest(Git git) + { + this.type = RequestType.GIT; + this.git = git; + } + + public ScanRequest(String repo, String ref) + { + this.git = new Git(repo, ref); + } + public ScanTask executeScan(){ + ScanTask st = new ScanTask(this); + st.execute(); + return st; + } + +} diff --git a/src/main/java/com/redhat/pctsec/model/ScanRequests.java b/src/main/java/com/redhat/pctsec/model/ScanRequests.java new file mode 100644 index 0000000..cf7095a --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/ScanRequests.java @@ -0,0 +1,111 @@ +package com.redhat.pctsec.model; + +import com.redhat.pctsec.model.api.request.pssaas; +import com.redhat.pctsec.model.api.request.scanChain; +import io.vertx.mutiny.core.eventbus.EventBus; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.*; +import java.util.stream.Collectors; + +import jakarta.persistence.*; + +@ApplicationScoped +@Entity +@Table(name="ScanRequests") +public class ScanRequests { + + @Id + @GeneratedValue + protected UUID id; + + @OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL) + @JoinColumn(name = "scan_request_id", referencedColumnName = "id") + private Set scanRequests;// = new HashSet<>(); + + + @Column(name="scan_properties") + private String globalScanProperties; + + @Column(name="scan_metadata") + private String scanMetadata; + + + public ScanRequests(){ + //Default to the Snyk scan + this.globalScanProperties = "-p snyk-only-unstable --tarball-build-script=\":\""; + this.scanRequests = new HashSet<>(); + } + + public ScanRequests(pssaas pssaas){ + this(); + pssaas.componentList.stream().filter(c -> c.getType().equals("git")).forEach(g -> this.addGit(g.getRepo().toString(), g.getRef())); + pssaas.componentList.stream().filter(c -> c.getType().equals("brew")).forEach(g -> this.addBrewBuild(g.getBuildId())); + pssaas.componentList.stream().filter(c -> c.getType().equals("pnc")).forEach(g -> this.addPNCBuild(g.getBuildId())); + } + + public ScanRequests(scanChain scanchain){ + this(); + } + + //public ScanRequests(String repo, String rev){ + // //shortcut for single scans + // scanRequests.add(new ScanRequest(repo, rev)); + //} + + /* + public ScanRequests(String brewBuildId){ + scanRequests.add(new ScanRequest(new B)); + } + */ + + public void addBrewBuild(String brewBuildId) + { + scanRequests.add(new ScanRequest(new BrewBuild(brewBuildId))); + } + + public void addGit(String repo, String rev) + { + scanRequests.add(new ScanRequest(new Git(repo, rev))); + } + + public void addPNCBuild(String pncBuildId) + { + scanRequests.add(new ScanRequest(new PNCBuild(pncBuildId))); + } + + //Create tekton pipeline/taskrun + public List execute(EventBus eventBus){ + scanRequests.stream().forEach(s -> s.setBus(eventBus)); + return scanRequests.stream().map(s -> s.executeScan()).collect(Collectors.toList()); + /* + for(ScanRequest s : scanRequests){ + s.executeScan(); + } + */ + } + + public Set getScanRequests() { + return scanRequests; + } + + public void setScanRequests(Set scanRequests) { + this.scanRequests = scanRequests; + } + + public String getGlobalScanProperties() { + return globalScanProperties; + } + + public void setGlobalScanProperties(String globalScanProperties) { + this.globalScanProperties = globalScanProperties; + } + + public String getScanMetadata() { + return scanMetadata; + } + + public void setScanMetadata(String scanMetadata) { + this.scanMetadata = scanMetadata; + } +} diff --git a/src/main/java/com/redhat/pctsec/model/ScanResult.java b/src/main/java/com/redhat/pctsec/model/ScanResult.java new file mode 100644 index 0000000..64c56ba --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/ScanResult.java @@ -0,0 +1,19 @@ +package com.redhat.pctsec.model; + +import java.net.URI; +import java.net.URL; + +public class ScanResult { + + public URL covScanTask; + + + //Store files in document store + private void storeResults(){ + + } + + private void fetchResults(){ + + } +} diff --git a/src/main/java/com/redhat/pctsec/model/ScanTask.java b/src/main/java/com/redhat/pctsec/model/ScanTask.java new file mode 100644 index 0000000..1ee2f97 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/ScanTask.java @@ -0,0 +1,78 @@ +package com.redhat.pctsec.model; + + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.vertx.core.eventbus.impl.EventBusImpl; +import io.vertx.mutiny.core.eventbus.EventBus; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.context.Dependent; +import jakarta.inject.Inject; +import jakarta.persistence.*; + +import java.util.UUID; + + +@Entity +@ApplicationScoped +public class ScanTask { + + @Id + @GeneratedValue + protected UUID id; + @JsonIgnore + @Transient + @Inject + EventBus bus; + public ScanTaskState state; + + public void setTektonRunId(String tektonRunId) { + this.tektonRunId = tektonRunId; + } + + public String tektonRunId; + + @OneToOne(fetch=FetchType.EAGER, cascade = CascadeType.ALL) + @JoinColumn(name = "scan_result_id", referencedColumnName = "id") + public ScanRequest scanRequest; + + + public ScanTask(ScanRequest scanRequest) { + this(); + this.scanRequest = scanRequest; + this.bus = scanRequest.getBus(); + //this.bus = new EventBus(new EventBusImpl()); + } + + + public ScanTask(){ + } + + + /* + public ScanTask(ScanRequest scanRequest) + { + this( + this.scanRequest = scanRequest; + } + + */ + public void execute(){ + bus.publish("tekton", this); + } + + public ScanTaskState getState() { + return state; + } + + public void setState(ScanTaskState state) { + this.state = state; + } + + public ScanRequest getScanRequest() { + return scanRequest; + } + + public void setScanRequest(ScanRequest scanRequest) { + this.scanRequest = scanRequest; + } +} diff --git a/src/main/java/com/redhat/pctsec/model/ScanTaskState.java b/src/main/java/com/redhat/pctsec/model/ScanTaskState.java new file mode 100644 index 0000000..6f4fa1a --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/ScanTaskState.java @@ -0,0 +1,3 @@ +package com.redhat.pctsec.model; + +public enum ScanTaskState {AWAIT, TRIGGERED, RUNNING, SUCCESS, FAULURE} diff --git a/src/main/java/com/redhat/pctsec/model/api/request/Component.java b/src/main/java/com/redhat/pctsec/model/api/request/Component.java new file mode 100644 index 0000000..7abc2d3 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/Component.java @@ -0,0 +1,17 @@ +package com.redhat.pctsec.model.api.request; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import java.net.URI; + +@JsonDeserialize(using = ComponentJsonDeserializer.class) +public interface Component { + + public String getType(); + + public String getBuildId(); + + public URI getRepo(); + + public String getRef(); +} diff --git a/src/main/java/com/redhat/pctsec/model/api/request/ComponentJsonDeserializer.java b/src/main/java/com/redhat/pctsec/model/api/request/ComponentJsonDeserializer.java new file mode 100644 index 0000000..d1b3699 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/ComponentJsonDeserializer.java @@ -0,0 +1,31 @@ +package com.redhat.pctsec.model.api.request; + +import com.fasterxml.jackson.core.JacksonException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; +import java.net.URI; + +public class ComponentJsonDeserializer extends JsonDeserializer { + + @Override + public Component deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException { + + JsonNode node = jsonParser.readValueAsTree(); + JsonNode componentT = node.get("type"); + if(componentT.asText().equals("git")) + { + URI repo = URI.create(node.get("repo").asText()); + String ref = node.get("ref").asText(); + return new git(repo, ref); + } + else + { + return new build(componentT.asText(), node.get("build-id").asText()); + } + + } +} diff --git a/src/main/java/com/redhat/pctsec/model/api/request/build.java b/src/main/java/com/redhat/pctsec/model/api/request/build.java new file mode 100644 index 0000000..b89d4ec --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/build.java @@ -0,0 +1,49 @@ +package com.redhat.pctsec.model.api.request; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import jakarta.validation.constraints.NotNull; + +import java.net.URI; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "type", + "build-id" +}) +public class build implements Component { + + public final String type; + + + public final String buildId; + + public build(@NotNull String type, @NotNull String buildId) { + this.type = type; + this.buildId = buildId; + } + + @Override + @NotNull + @JsonProperty("type") + public String getType() { + return this.type; + } + + @NotNull + @JsonProperty("build-id") + @Override + public String getBuildId() { + return this.buildId; + } + + @Override + public URI getRepo() { + return URI.create(""); + } + + @Override + public String getRef() { + return ""; + } +} diff --git a/src/main/java/com/redhat/pctsec/model/api/request/git.java b/src/main/java/com/redhat/pctsec/model/api/request/git.java new file mode 100644 index 0000000..33a2c81 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/git.java @@ -0,0 +1,53 @@ +package com.redhat.pctsec.model.api.request; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import jakarta.validation.constraints.NotNull; + +import java.net.URI; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "type", + "repo", + "ref" +}) +public class git implements Component{ + @NotNull + @JsonProperty("type") + public final static String type = "git"; + + @NotNull + @JsonProperty("repo") + public URI repo; + + @NotNull + @JsonProperty("ref") + public String ref; + + public git(@NotNull URI repo, @NotNull String ref) { + this.repo = repo; + this.ref = ref; + } + + @Override + public String getType() { + return this.type; + } + + @Override + public String getBuildId() { + return ""; + } + + @Override + public URI getRepo() { + return this.repo; + } + + @Override + public String getRef() { + return this.ref; + } +} \ No newline at end of file diff --git a/src/main/java/com/redhat/pctsec/model/api/request/pssaas.java b/src/main/java/com/redhat/pctsec/model/api/request/pssaas.java new file mode 100644 index 0000000..292353b --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/pssaas.java @@ -0,0 +1,70 @@ +package com.redhat.pctsec.model.api.request; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyDescription; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +public class pssaas { + /** + * The product ID associated with the scan. + * (Required) + * + */ + @JsonProperty("product-id") + @JsonPropertyDescription("The product ID associated with the scan.") + @NotNull + public String productId; + /** + * The submission event ID associated with the scan. + * + */ + @JsonProperty("event-id") + @JsonPropertyDescription("The submission event ID associated with the scan.") + public String eventId; + /** + * Indicates whether or not the product is a managed service. + * (Required) + * + */ + @JsonProperty("is-managed-service") + @JsonPropertyDescription("Indicates whether or not the product is a managed service.") + @NotNull + public Boolean isManagedService; + /** + * The version of CPaaS that submitted the scan. + * + */ + @JsonProperty("cpaas-version") + @JsonPropertyDescription("The version of CPaaS that submitted the scan.") + public String cpaasVersion; + /** + * URL of Jenkins job that submitted the scan. + * + */ + @JsonProperty("job-url") + @JsonPropertyDescription("URL of Jenkins job that submitted the scan.") + public String jobUrl; + /** + * List of components to be scanned. + * (Required) + * + */ + @JsonProperty("component-list") + @JsonDeserialize(as = java.util.LinkedHashSet.class) + @JsonPropertyDescription("List of components to be scanned.") + @Size(min = 1) + @Valid + @NotNull + public Set componentList; + +} diff --git a/src/main/java/com/redhat/pctsec/model/api/request/scanChain.java b/src/main/java/com/redhat/pctsec/model/api/request/scanChain.java new file mode 100644 index 0000000..1040148 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/api/request/scanChain.java @@ -0,0 +1,4 @@ +package com.redhat.pctsec.model.api.request; + +public class scanChain { +} diff --git a/src/main/java/com/redhat/pctsec/model/jpa/ScanRepository.java b/src/main/java/com/redhat/pctsec/model/jpa/ScanRepository.java new file mode 100644 index 0000000..1be51a3 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/jpa/ScanRepository.java @@ -0,0 +1,16 @@ +package com.redhat.pctsec.model.jpa; + +import com.redhat.pctsec.model.Scan; +import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; +import io.smallrye.mutiny.Uni; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.UUID; + +@ApplicationScoped +public class ScanRepository implements PanacheRepositoryBase { + public Uni findByProduct(String product) + { + return find("product", product).firstResult(); + } +} diff --git a/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestRepository.java b/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestRepository.java new file mode 100644 index 0000000..7e83c83 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestRepository.java @@ -0,0 +1,18 @@ +package com.redhat.pctsec.model.jpa; + + +import com.redhat.pctsec.model.ScanRequest; +import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; +import io.smallrye.mutiny.Uni; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.UUID; + +@ApplicationScoped +public class ScanRequestRepository implements PanacheRepositoryBase { + public Uni findByProduct(String product) + { + return find("product", product).firstResult(); + } +} + diff --git a/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestsRepository.java b/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestsRepository.java new file mode 100644 index 0000000..2a9f936 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/jpa/ScanRequestsRepository.java @@ -0,0 +1,18 @@ +package com.redhat.pctsec.model.jpa; + +import com.redhat.pctsec.model.Scan; +import com.redhat.pctsec.model.ScanRequests; +import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; +import io.smallrye.mutiny.Uni; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.UUID; + +@ApplicationScoped +public class ScanRequestsRepository implements PanacheRepositoryBase { + public Uni findByProduct(String product) + { + return find("product", product).firstResult(); + } +} + diff --git a/src/main/java/com/redhat/pctsec/model/jpa/UriConverter.java b/src/main/java/com/redhat/pctsec/model/jpa/UriConverter.java new file mode 100644 index 0000000..c96d21f --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/jpa/UriConverter.java @@ -0,0 +1,22 @@ +package com.redhat.pctsec.model.jpa; + +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; + + +import java.net.URI; + +@Converter(autoApply = true) +public class UriConverter implements AttributeConverter +{ + + @Override + public String convertToDatabaseColumn(URI uri) { + return (uri == null) ? null : uri.toString(); + } + + @Override + public URI convertToEntityAttribute(String s) { + return ((s.length() > 0) ? URI.create(s.trim()) : null); + } +} diff --git a/src/main/java/com/redhat/pctsec/model/osh/paramMapper.java b/src/main/java/com/redhat/pctsec/model/osh/paramMapper.java new file mode 100644 index 0000000..dc0ed64 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/model/osh/paramMapper.java @@ -0,0 +1,72 @@ +package com.redhat.pctsec.model.osh; + +import jakarta.inject.Singleton; +import picocli.CommandLine; +import picocli.CommandLine.Option; +import picocli.CommandLine.Parameters; + + + +public class paramMapper { + + @Option(names = {"-p", "--profile"}, description = "list of analyzers to use (see command 'list-\n" + + " analyzers'); use comma as a separator: e.g. \"\n" + + " --analyzer=gcc,clang,cppcheck\"") + private String profile; + + @Option(names = {"-a", "--analyzer"}, description = "list of analyzers to use (see command 'list-\n" + + " analyzers'); use comma as a separator: e.g. \"\n" + + " --analyzer=gcc,clang,cppcheck\"") + private String analyzers; + + @Option(names = {"--tarball-build-script"}, description = "With this option osh-cli accepts path to\n" + + " tarball specified via first argument and then\n" + + " the tarball will be scanned. This option sets\n" + + " command which should build the package,\n" + + " usually this should be just \"make\", in case\n" + + " of packages which doesn't need to be built,\n" + + " just pass \"true\".\n") + private String tarballBuildScript; + + @Option(names = {"--brew-build"}, description = "use a brew build (specified by NVR) instead\n" + + " of a local file") + private String brewBuild; + + public paramMapper(){} + + public paramMapper(String params){ + new CommandLine(this).parseArgs(params.split(("\\s+"))); + } + + public String getProfile() { + return profile; + } + + public void setProfile(String profile) { + this.profile = profile; + } + + public String getAnalyzers() { + return analyzers; + } + + public void setAnalyzers(String analyzers) { + this.analyzers = analyzers; + } + + public String getTarballBuildScript() { + return tarballBuildScript; + } + + public void setTarballBuildScript(String tarballBuildScript) { + this.tarballBuildScript = tarballBuildScript; + } + + public String getBrewBuild() { + return brewBuild; + } + + public void setBrewBuild(String brewBuild) { + this.brewBuild = brewBuild; + } +} diff --git a/src/main/java/rest/UsersResource.java b/src/main/java/com/redhat/pctsec/rest/v1alpha1/Kerberos.java similarity index 51% rename from src/main/java/rest/UsersResource.java rename to src/main/java/com/redhat/pctsec/rest/v1alpha1/Kerberos.java index e62f7ef..0f337e3 100644 --- a/src/main/java/rest/UsersResource.java +++ b/src/main/java/com/redhat/pctsec/rest/v1alpha1/Kerberos.java @@ -1,29 +1,18 @@ -package rest; +package com.redhat.pctsec.rest.v1alpha1; -import dto.ConnectDB; -import dto.ScanObj; -import io.quarkus.arc.profile.UnlessBuildProfile; import io.quarkiverse.kerberos.KerberosPrincipal; +import io.quarkus.arc.profile.UnlessBuildProfile; import io.quarkus.security.Authenticated; import io.quarkus.security.identity.SecurityIdentity; - -import javax.inject.Inject; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Set; -import javax.ws.rs.Produces; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; @UnlessBuildProfile("dev") -@Path("/testKerberos") +@Path("/Kerberos") @Authenticated -public class UsersResource { +public class Kerberos { @Inject SecurityIdentity identity; @Inject diff --git a/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestResource.java b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestResource.java new file mode 100644 index 0000000..c321b63 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestResource.java @@ -0,0 +1,50 @@ +package com.redhat.pctsec.rest.v1alpha1; + +import com.redhat.pctsec.model.ScanRequest; +import com.redhat.pctsec.model.jpa.ScanRequestRepository; +import com.redhat.pctsec.model.osh.paramMapper; +import io.quarkus.security.Authenticated; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import jakarta.ws.rs.*; +import picocli.CommandLine; + +import java.util.UUID; +@ApplicationScoped +@Path("/api/v1a/ScanRequest/{id}") +public class ScanRequestResource { + @Inject + ScanRequestRepository scanRequestRepository; + + + @GET + @Produces({"application/json"}) + public ScanRequest getScanRequest(String id) + { + ScanRequest scanRequest = scanRequestRepository.findById(UUID.fromString(id)); + return scanRequest; + } + + @PATCH + @Path("ScanProperties/{scanProperties}") + @Consumes({"application/octet-stream"}) + @Produces({"application/json"}) + @Authenticated + @Transactional + public ScanRequest patchScanRequest(String id, String scanProperties) + { + ScanRequest scanRequest = scanRequestRepository.findById(UUID.fromString(id)); + + try { + paramMapper pm = new paramMapper(scanProperties); + }catch(CommandLine.UnmatchedArgumentException e) + { + throw new BadRequestException("Invalid OSH Parameter"); + } + scanRequest.setScanProperties(scanProperties); + scanRequestRepository.persist(scanRequest); + return scanRequest; + } + +} diff --git a/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestsResource.java b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestsResource.java new file mode 100644 index 0000000..6b26743 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanRequestsResource.java @@ -0,0 +1,41 @@ +package com.redhat.pctsec.rest.v1alpha1; + +import com.redhat.pctsec.model.Scan; +import com.redhat.pctsec.model.ScanRequest; +import com.redhat.pctsec.model.ScanRequests; +import com.redhat.pctsec.model.jpa.ScanRepository; +import com.redhat.pctsec.model.jpa.ScanRequestsRepository; +import io.quarkus.security.Authenticated; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.*; +import org.jboss.resteasy.reactive.common.NotImplementedYet; + +import java.util.UUID; + +@ApplicationScoped +@Path("/api/v1a/ScanRequests/{id}") +public class ScanRequestsResource { + + @Inject + ScanRequestsRepository sr; + + + @GET + @Produces({"application/json"}) + public ScanRequests getScanRequests(String id) + { + ScanRequests scanRequests = sr.findById(UUID.fromString(id)); + return scanRequests; + } + + @POST + @Produces({"application/json"}) + @Consumes({"application/json"}) + @Authenticated + public ScanRequests addScanRequest(String id, ScanRequest scanRequest) + { + throw new NotImplementedYet(); + } + +} diff --git a/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanResource.java b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanResource.java new file mode 100644 index 0000000..80ade42 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/rest/v1alpha1/ScanResource.java @@ -0,0 +1,122 @@ +package com.redhat.pctsec.rest.v1alpha1; + +import com.redhat.pctsec.model.*; +import com.redhat.pctsec.model.api.request.pssaas; +import com.redhat.pctsec.model.jpa.ScanRepository; +import io.quarkus.security.Authenticated; +import io.vertx.mutiny.core.eventbus.EventBus; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import jakarta.validation.Valid; +import jakarta.ws.rs.*; +import org.jboss.resteasy.reactive.RestQuery; + +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@ApplicationScoped +@Path("/api/v1a/Scan") +public class ScanResource { + + @Inject + ScanRepository sr; + + @Inject + EventBus bus; + + @POST + @Path("PSSaaS") + @Consumes({ "application/json" }) + @Transactional + @Authenticated + public Scan createPSSAAS(@Valid pssaas scanRequest) + { + ScanRequests scanRequests = new ScanRequests(scanRequest); + Scan s = new Scan(); + s.setRequestor("cpaas"); + s.setScanRequests(scanRequests); + sr.persist(s); + return s; + } + @POST + @Path("PSSaaS/run") + @Consumes({ "application/json" }) + @Transactional + @Authenticated + public List createRunPSSAAS(@Valid pssaas scanRequest) + { + Scan s = this.createPSSAAS(scanRequest); + return s.scanRequests.execute(bus); + } + + @GET + @Path("All") + @Produces({"application/json"}) + public List list() + { + return sr.listAll(); + } + + @GET + @Path("{id}") + @Produces({"application/json"}) + public Scan scanRequest(String id) + { + Scan s = sr.findById(UUID.fromString(id)); + return s; + } + + @GET + @Path("{id}/run") + @Authenticated + public List scanRequestExe(String id) + { + Scan s = sr.findById(UUID.fromString(id)); + return s.scanRequests.execute(bus); + } + + + @GET + @Path("single/git") + @Produces({"application/json"}) + @Transactional + @Authenticated + public Scan singleGit(@RestQuery String repo, @RestQuery String ref) + { + Scan s = new Scan(); + s.setRequestor("jochrist"); + s.getScanRequests().addGit(repo,ref); + sr.persist(s); + return s; + } + + @GET + @Path("single/brew") + @Produces({"application/json"}) + @Transactional + @Authenticated + public Scan singleGit(@RestQuery String brewId) + { + Scan s = new Scan(); + s.setRequestor("jochrist"); + s.getScanRequests().addBrewBuild(brewId); + sr.persist(s); + return s; + } + @GET + @Path("single/pnc") + @Produces({"application/json"}) + @Transactional + @Authenticated + public Scan singlePNC(@RestQuery String pncId) + { + Scan s = new Scan(); + s.setRequestor("jochrist"); + s.getScanRequests().addPNCBuild(pncId); + sr.persist(s); + return s; + } +} diff --git a/src/main/java/com/redhat/pctsec/tekton/TaskHandler.java b/src/main/java/com/redhat/pctsec/tekton/TaskHandler.java new file mode 100644 index 0000000..b240716 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/tekton/TaskHandler.java @@ -0,0 +1,139 @@ +package com.redhat.pctsec.tekton; +import com.redhat.pctsec.model.RequestType; +import com.redhat.pctsec.model.ScanTask; +import com.redhat.pctsec.model.ScanTaskState; +import io.fabric8.kubernetes.api.model.ConfigMapVolumeSource; +import io.fabric8.kubernetes.api.model.PersistentVolumeClaimVolumeSource; +import io.fabric8.kubernetes.api.model.PodSecurityContext; +import io.fabric8.kubernetes.api.model.PodSecurityContextBuilder; +import io.fabric8.tekton.client.DefaultTektonClient; +import io.fabric8.tekton.client.TektonClient; +import io.fabric8.tekton.client.DefaultTektonClient; +import io.fabric8.tekton.client.TektonClient; +import io.fabric8.tekton.pipeline.v1beta1.*; + +import io.quarkus.vertx.ConsumeEvent; + +import io.smallrye.common.annotation.Blocking; +import jakarta.inject.Inject; + +import org.apache.commons.lang3.RandomStringUtils; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +import java.util.ArrayList; +import java.util.List; + +public class TaskHandler { + + @ConfigProperty(name = "quarkus.openshift.namespace") + String NAMESPACE; + @ConfigProperty(name = "tekton.pipeline.ref") + String PIPELINE_REFERENCE; + @ConfigProperty(name = "tekton.service-account") + String SERVICE_ACCOUNT; + + @ConfigProperty(name = "tekton.task.ref") + String TASK_REFERENCE; + + @Inject + TektonClient tektonClient; + + @ConsumeEvent("tekton") + @Blocking + public ScanTask consume(ScanTask scanTask) + { + + switch(scanTask.getScanRequest().getType()) + { + case BREW: + scanTask.setTektonRunId(invokeScanTask(scanTask.getScanRequest().brewBuild.buildRef)); + scanTask.setState(ScanTaskState.RUNNING); + break; + + case PNC: + String repo = scanTask.getScanRequest().pncBuild.SCMURL().toString(); + String ref = scanTask.getScanRequest().pncBuild.revision(); + scanTask.setTektonRunId(invokeOshScmScanPipeline(repo, ref)); + scanTask.setState(ScanTaskState.RUNNING); + break; + + case GIT: + scanTask.setTektonRunId(invokeOshScmScanPipeline(scanTask.getScanRequest().git.repo.toString(), scanTask.getScanRequest().git.ref)); + scanTask.setState(ScanTaskState.RUNNING); + break; + } + + return scanTask; + } + + public String invokeScanTask(String buildId) { + // String buildId = "xterm-366-8.el9"; + String scanProfile = "snyk-only-unstable"; + + // random taskrun name generating for now + TaskRun taskRun = new TaskRunBuilder().withNewMetadata().withName("osh-scan-taskrun-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase()) + .endMetadata() + .withNewSpec() + .withServiceAccountName(SERVICE_ACCOUNT) + .withNewTaskRef() + .withName(TASK_REFERENCE) + .endTaskRef() + .withParams( + new Param("buildId", new ArrayOrString(buildId)), + new Param("scanProfile", new ArrayOrString(scanProfile))) + .endSpec() + .build(); + + tektonClient.v1beta1().taskRuns().inNamespace(NAMESPACE).resource(taskRun).create(); + + return taskRun.getMetadata().getName(); + } + + public String invokeOshScmScanPipeline(String repo, String ref) { + + PodSecurityContext securityContext = new PodSecurityContextBuilder() + .withRunAsNonRoot(true) + .withRunAsUser(65532L) + .build(); + + WorkspaceBinding sourcesWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("sources") + .withPersistentVolumeClaim(new PersistentVolumeClaimVolumeSource("osh-client-sources", null)) + .build(); + + WorkspaceBinding sourceTarsWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("source-tars") + .withPersistentVolumeClaim(new PersistentVolumeClaimVolumeSource("osh-client-source-tars", null)) + .build(); + + WorkspaceBinding sslCaDirectoryWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("ssl-ca-directory") + .withConfigMap(new ConfigMapVolumeSource(null, null, "config-trusted-cabundle", null)) + .build(); + + List workspaceBindings = new ArrayList<>(); + workspaceBindings.add(sourcesWorkspaceBinding); + workspaceBindings.add(sourceTarsWorkspaceBinding); + workspaceBindings.add(sslCaDirectoryWorkspaceBinding); + + PipelineRun pipelineRun = new PipelineRunBuilder() + .withNewMetadata().withName("osh-scm-scan-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase()).endMetadata() + .withNewSpec() + .withNewPodTemplate() + .withSecurityContext(securityContext) + .endPodTemplate() + .withServiceAccountName(SERVICE_ACCOUNT) + .withNewPipelineRef().withName(PIPELINE_REFERENCE).endPipelineRef() + .addNewParam().withName("repo-url").withNewValue(repo).endParam() + .addNewParam().withName("revision").withNewValue(ref).endParam() + .withWorkspaces(workspaceBindings) + .endSpec() + .build(); + + tektonClient.v1beta1().pipelineRuns().inNamespace(NAMESPACE).resource(pipelineRun).create(); + + return pipelineRun.getMetadata().getName(); + } + + +} diff --git a/src/main/java/com/redhat/pctsec/tekton/brewTaskRun.java b/src/main/java/com/redhat/pctsec/tekton/brewTaskRun.java new file mode 100644 index 0000000..5249382 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/tekton/brewTaskRun.java @@ -0,0 +1,49 @@ +package com.redhat.pctsec.tekton; + +import io.fabric8.tekton.client.DefaultTektonClient; +import io.fabric8.tekton.client.TektonClient; +import io.fabric8.tekton.pipeline.v1beta1.ArrayOrString; +import io.fabric8.tekton.pipeline.v1beta1.Param; +import io.fabric8.tekton.pipeline.v1beta1.TaskRun; +import io.fabric8.tekton.pipeline.v1beta1.TaskRunBuilder; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Singleton; +import org.apache.commons.lang3.RandomStringUtils; + +import jakarta.inject.Inject; + +@io.quarkus.arc.Unremovable +public class brewTaskRun { + public static final String NAMESPACE = "pct-security-tooling"; + public static final String BUILD_ID = "buildId"; + public static final String SCAN_PROFILE = "scanProfile"; + public static final String TASK_REFERENCE = "osh-scan-task"; + public static final String SERVICE_ACCOUNT = "osh-wrapper-client-sa"; + + //@Inject + TektonClient tektonClient = new DefaultTektonClient(); + + public String invokeScanTask(String buildId) { + // String buildId = "xterm-366-8.el9"; + String scanProfile = "snyk-only-unstable"; + + // random taskrun name generating for now + TaskRun taskRun = new TaskRunBuilder().withNewMetadata().withName("osh-scan-taskrun-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase()) + .endMetadata() + .withNewSpec() + .withServiceAccountName(SERVICE_ACCOUNT) + .withNewTaskRef() + .withName(TASK_REFERENCE) + .endTaskRef() + .withParams( + new Param("buildId", new ArrayOrString(buildId)), + new Param("scanProfile", new ArrayOrString(scanProfile))) + .endSpec() + .build(); + + tektonClient.v1beta1().taskRuns().inNamespace(NAMESPACE).resource(taskRun).create(); + + return "Scan invoked"; + } + +} diff --git a/src/main/java/com/redhat/pctsec/tekton/scmUrlPipelineRun.java b/src/main/java/com/redhat/pctsec/tekton/scmUrlPipelineRun.java new file mode 100644 index 0000000..7531e03 --- /dev/null +++ b/src/main/java/com/redhat/pctsec/tekton/scmUrlPipelineRun.java @@ -0,0 +1,74 @@ +package com.redhat.pctsec.tekton; + +import io.fabric8.kubernetes.api.model.ConfigMapVolumeSource; +import io.fabric8.kubernetes.api.model.PersistentVolumeClaimVolumeSource; +import io.fabric8.kubernetes.api.model.PodSecurityContext; +import io.fabric8.kubernetes.api.model.PodSecurityContextBuilder; +import io.fabric8.tekton.client.DefaultTektonClient; +import io.fabric8.tekton.client.TektonClient; +import io.fabric8.tekton.client.DefaultTektonClient; +import io.fabric8.tekton.client.TektonClient; +import io.fabric8.tekton.pipeline.v1beta1.*; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Singleton; +import org.apache.commons.lang3.RandomStringUtils; + +import java.util.ArrayList; +import java.util.List; + +public class scmUrlPipelineRun { + public static final String NAMESPACE = "pct-security-tooling"; + public static final String REPO_URL = "repo-url"; + public static final String REVISION = "revision"; + public static final String PIPELINE_REFERENCE = "osh-client-from-source"; + public static final String SERVICE_ACCOUNT = "osh-wrapper-client-sa"; + + TektonClient tektonClient = new DefaultTektonClient(); + + public String invokeOshScmScanPipeline(String repo, String ref) { + + PodSecurityContext securityContext = new PodSecurityContextBuilder() + .withRunAsNonRoot(true) + .withRunAsUser(65532L) + .build(); + + WorkspaceBinding sourcesWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("sources") + .withPersistentVolumeClaim(new PersistentVolumeClaimVolumeSource("osh-client-sources", null)) + .build(); + + WorkspaceBinding sourceTarsWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("source-tars") + .withPersistentVolumeClaim(new PersistentVolumeClaimVolumeSource("osh-client-source-tars", null)) + .build(); + + WorkspaceBinding sslCaDirectoryWorkspaceBinding = new WorkspaceBindingBuilder() + .withName("ssl-ca-directory") + .withConfigMap(new ConfigMapVolumeSource(null, null, "config-trusted-cabundle", null)) + .build(); + + List workspaceBindings = new ArrayList<>(); + workspaceBindings.add(sourcesWorkspaceBinding); + workspaceBindings.add(sourceTarsWorkspaceBinding); + workspaceBindings.add(sslCaDirectoryWorkspaceBinding); + + PipelineRun pipelineRun = new PipelineRunBuilder() + .withNewMetadata().withName("osh-scm-scan-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase()).endMetadata() + .withNewSpec() + .withNewPodTemplate() + .withSecurityContext(securityContext) + .endPodTemplate() + .withServiceAccountName(SERVICE_ACCOUNT) + .withNewPipelineRef().withName(PIPELINE_REFERENCE).endPipelineRef() + .addNewParam().withName(REPO_URL).withNewValue(repo).endParam() + .addNewParam().withName(REVISION).withNewValue(ref).endParam() + .withWorkspaces(workspaceBindings) + .endSpec() + .build(); + + tektonClient.v1beta1().pipelineRuns().inNamespace(NAMESPACE).resource(pipelineRun).create(); + + return "Scan invoked. PipelineRun name: " + pipelineRun.getMetadata().getName(); + } + +} diff --git a/src/main/java/constants/HttpHeaders.java b/src/main/java/constants/HttpHeaders.java deleted file mode 100644 index 11fb4b9..0000000 --- a/src/main/java/constants/HttpHeaders.java +++ /dev/null @@ -1,92 +0,0 @@ -package constants; - -/** - * Copied from io.undertow.util.Headers - */ -public class HttpHeaders { - - public static final String ACCEPT_STRING = "Accept"; - public static final String ACCEPT_CHARSET_STRING = "Accept-Charset"; - public static final String ACCEPT_ENCODING_STRING = "Accept-Encoding"; - public static final String ACCEPT_LANGUAGE_STRING = "Accept-Language"; - public static final String ACCEPT_RANGES_STRING = "Accept-Ranges"; - public static final String AGE_STRING = "Age"; - public static final String ALLOW_STRING = "Allow"; - public static final String AUTHENTICATION_INFO_STRING = "Authentication-Info"; - public static final String AUTHORIZATION_STRING = "Authorization"; - public static final String CACHE_CONTROL_STRING = "Cache-Control"; - public static final String COOKIE_STRING = "Cookie"; - public static final String COOKIE2_STRING = "Cookie2"; - public static final String CONNECTION_STRING = "Connection"; - public static final String CONTENT_DISPOSITION_STRING = "Content-Disposition"; - public static final String CONTENT_ENCODING_STRING = "Content-Encoding"; - public static final String CONTENT_LANGUAGE_STRING = "Content-Language"; - public static final String CONTENT_LENGTH_STRING = "Content-Length"; - public static final String CONTENT_LOCATION_STRING = "Content-Location"; - public static final String CONTENT_MD5_STRING = "Content-MD5"; - public static final String CONTENT_RANGE_STRING = "Content-Range"; - public static final String CONTENT_SECURITY_POLICY_STRING = "Content-Security-Policy"; - public static final String CONTENT_TYPE_STRING = "Content-Type"; - public static final String DATE_STRING = "Date"; - public static final String ETAG_STRING = "ETag"; - public static final String EXPECT_STRING = "Expect"; - public static final String EXPIRES_STRING = "Expires"; - public static final String FORWARDED_STRING = "Forwarded"; - public static final String FROM_STRING = "From"; - public static final String HOST_STRING = "Host"; - public static final String IF_MATCH_STRING = "If-Match"; - public static final String IF_MODIFIED_SINCE_STRING = "If-Modified-Since"; - public static final String IF_NONE_MATCH_STRING = "If-None-Match"; - public static final String IF_RANGE_STRING = "If-Range"; - public static final String IF_UNMODIFIED_SINCE_STRING = "If-Unmodified-Since"; - public static final String LAST_MODIFIED_STRING = "Last-Modified"; - public static final String LOCATION_STRING = "Location"; - public static final String MAX_FORWARDS_STRING = "Max-Forwards"; - public static final String ORIGIN_STRING = "Origin"; - public static final String PRAGMA_STRING = "Pragma"; - public static final String PROXY_AUTHENTICATE_STRING = "Proxy-Authenticate"; - public static final String PROXY_AUTHORIZATION_STRING = "Proxy-Authorization"; - public static final String RANGE_STRING = "Range"; - public static final String REFERER_STRING = "Referer"; - public static final String REFERRER_POLICY_STRING = "Referrer-Policy"; - public static final String REFRESH_STRING = "Refresh"; - public static final String RETRY_AFTER_STRING = "Retry-After"; - public static final String SEC_WEB_SOCKET_ACCEPT_STRING = "Sec-WebSocket-Accept"; - public static final String SEC_WEB_SOCKET_EXTENSIONS_STRING = "Sec-WebSocket-Extensions"; - public static final String SEC_WEB_SOCKET_KEY_STRING = "Sec-WebSocket-Key"; - public static final String SEC_WEB_SOCKET_KEY1_STRING = "Sec-WebSocket-Key1"; - public static final String SEC_WEB_SOCKET_KEY2_STRING = "Sec-WebSocket-Key2"; - public static final String SEC_WEB_SOCKET_LOCATION_STRING = "Sec-WebSocket-Location"; - public static final String SEC_WEB_SOCKET_ORIGIN_STRING = "Sec-WebSocket-Origin"; - public static final String SEC_WEB_SOCKET_PROTOCOL_STRING = "Sec-WebSocket-Protocol"; - public static final String SEC_WEB_SOCKET_VERSION_STRING = "Sec-WebSocket-Version"; - public static final String SERVER_STRING = "Server"; - public static final String SERVLET_ENGINE_STRING = "Servlet-Engine"; - public static final String SET_COOKIE_STRING = "Set-Cookie"; - public static final String SET_COOKIE2_STRING = "Set-Cookie2"; - public static final String SSL_CLIENT_CERT_STRING = "SSL_CLIENT_CERT"; - public static final String SSL_CIPHER_STRING = "SSL_CIPHER"; - public static final String SSL_SESSION_ID_STRING = "SSL_SESSION_ID"; - public static final String SSL_CIPHER_USEKEYSIZE_STRING = "SSL_CIPHER_USEKEYSIZE"; - public static final String STATUS_STRING = "Status"; - public static final String STRICT_TRANSPORT_SECURITY_STRING = "Strict-Transport-Security"; - public static final String TE_STRING = "TE"; - public static final String TRAILER_STRING = "Trailer"; - public static final String TRANSFER_ENCODING_STRING = "Transfer-Encoding"; - public static final String UPGRADE_STRING = "Upgrade"; - public static final String USER_AGENT_STRING = "User-Agent"; - public static final String VARY_STRING = "Vary"; - public static final String VIA_STRING = "Via"; - public static final String WARNING_STRING = "Warning"; - public static final String WWW_AUTHENTICATE_STRING = "WWW-Authenticate"; - public static final String X_CONTENT_TYPE_OPTIONS_STRING = "X-Content-Type-Options"; - public static final String X_DISABLE_PUSH_STRING = "X-Disable-Push"; - public static final String X_FORWARDED_FOR_STRING = "X-Forwarded-For"; - public static final String X_FORWARDED_PROTO_STRING = "X-Forwarded-Proto"; - public static final String X_FORWARDED_HOST_STRING = "X-Forwarded-Host"; - public static final String X_FORWARDED_PORT_STRING = "X-Forwarded-Port"; - public static final String X_FORWARDED_SERVER_STRING = "X-Forwarded-Server"; - public static final String X_FRAME_OPTIONS_STRING = "X-Frame-Options"; - public static final String X_XSS_PROTECTION_STRING = "X-Xss-Protection"; - -} \ No newline at end of file diff --git a/src/main/java/constants/PSGQL.java b/src/main/java/constants/PSGQL.java deleted file mode 100644 index af8dcd1..0000000 --- a/src/main/java/constants/PSGQL.java +++ /dev/null @@ -1,7 +0,0 @@ -package constants; - -public class PSGQL { - public static final String url = "jdbc:postgresql://localhost:5432/mydb"; - public static final String user = "postgres"; - public static final String password = "password"; -} \ No newline at end of file diff --git a/src/main/java/dto/BrewObj.java b/src/main/java/dto/BrewObj.java deleted file mode 100644 index 0497751..0000000 --- a/src/main/java/dto/BrewObj.java +++ /dev/null @@ -1,29 +0,0 @@ -package dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.ToString; -import lombok.extern.jackson.Jacksonized; - -import java.io.Serializable; - -@AllArgsConstructor -@Builder -@Getter -@ToString -@Jacksonized -public class BrewObj implements Serializable { - - public static final String SQL = "INSERT INTO brewscans " + - "(build_system_type, brew_id, brew_nvr, pnc_id, artifact_type, file_name, built_from_source)" + - "VALUES (? ? ? ? ? ? ?)"; - - private final String buildSystemType; - private final String brewId; - private final String brewNvr; - private final String pncId; - private final String artifactType; - private final String fileName; - private final Boolean builtFromSource; -} diff --git a/src/main/java/dto/BrewObjPayload.java b/src/main/java/dto/BrewObjPayload.java deleted file mode 100644 index 07f41ff..0000000 --- a/src/main/java/dto/BrewObjPayload.java +++ /dev/null @@ -1,20 +0,0 @@ -package dto; - -import org.json.JSONException; -import org.json.JSONObject; - -public class BrewObjPayload { - - public static BrewObj constructScanPayload(JSONObject jsonObj) throws JSONException { - return new BrewObj( - jsonObj.getString("build_system_type"), - jsonObj.getString("brew_id"), - jsonObj.getString("brew_nvr"), - jsonObj.getString("pnc_id"), - jsonObj.getString("artifact_type"), - jsonObj.getString("file_name"), - jsonObj.getBoolean("built_from_source")); - } - - private BrewObjPayload() {} -} diff --git a/src/main/java/dto/ConnectDB.java b/src/main/java/dto/ConnectDB.java deleted file mode 100644 index 1944770..0000000 --- a/src/main/java/dto/ConnectDB.java +++ /dev/null @@ -1,25 +0,0 @@ -package dto; - -import org.json.JSONException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import static constants.PSGQL.*; - -// @TODO Replace hard-coded credentials; make use of our secure db connection practice - -public class ConnectDB { - - public Connection connect() throws JSONException { - try { - Connection conn = DriverManager.getConnection(url, user, password); - System.out.println("Connected to PostgreSQL server"); - return conn; - } catch (SQLException e) { - System.out.println(e.getMessage()); - } - return null; - } -} diff --git a/src/main/java/dto/GitObj.java b/src/main/java/dto/GitObj.java deleted file mode 100644 index 81f8d3f..0000000 --- a/src/main/java/dto/GitObj.java +++ /dev/null @@ -1,25 +0,0 @@ -package dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.ToString; -import lombok.extern.jackson.Jacksonized; -import java.io.Serializable; - -@AllArgsConstructor -@Builder -@Getter -@ToString -@Jacksonized -public class GitObj implements Serializable { - - public static final String SQL = "INSERT INTO gitscans " + - "(build_system_type, repository, reference, commit_id)" + - "VALUES (? ? ? ?)"; - - private final String buildSystemType; - private final String repository; - private final String reference; - private final String commitId; -} \ No newline at end of file diff --git a/src/main/java/dto/GitObjPayload.java b/src/main/java/dto/GitObjPayload.java deleted file mode 100644 index eaabab1..0000000 --- a/src/main/java/dto/GitObjPayload.java +++ /dev/null @@ -1,17 +0,0 @@ -package dto; - -import org.json.JSONException; -import org.json.JSONObject; - -public class GitObjPayload { - - public static GitObj constructScanPayload(JSONObject jsonObj) throws JSONException { - return new GitObj( - jsonObj.getString("build_system_type"), - jsonObj.getString("repository"), - jsonObj.getString("reference"), - jsonObj.getString("commit_id")); - } - - private GitObjPayload() {} -} diff --git a/src/main/java/dto/PncObj.java b/src/main/java/dto/PncObj.java deleted file mode 100644 index 14b9f7d..0000000 --- a/src/main/java/dto/PncObj.java +++ /dev/null @@ -1,21 +0,0 @@ -package dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.ToString; -import lombok.extern.jackson.Jacksonized; -import java.io.Serializable; - -@AllArgsConstructor -@Builder -@Getter -@ToString -@Jacksonized -public class PncObj implements Serializable { - - public static final String SQL = "INSERT INTO pncscans (build_system_type, build_id) VALUES (? ?)"; - - private final String buildSystemType; - private final String buildId; -} \ No newline at end of file diff --git a/src/main/java/dto/PncObjPayload.java b/src/main/java/dto/PncObjPayload.java deleted file mode 100644 index a8f313c..0000000 --- a/src/main/java/dto/PncObjPayload.java +++ /dev/null @@ -1,15 +0,0 @@ -package dto; - -import org.json.JSONException; -import org.json.JSONObject; - -public class PncObjPayload { - - public static PncObj constructScanPayload(JSONObject jsonObj) throws JSONException { - return new PncObj( - jsonObj.getString("build_system_type"), - jsonObj.getString("build_id")); - } - - private PncObjPayload() {} -} diff --git a/src/main/java/dto/ScanInterface.java b/src/main/java/dto/ScanInterface.java deleted file mode 100644 index a435f62..0000000 --- a/src/main/java/dto/ScanInterface.java +++ /dev/null @@ -1,9 +0,0 @@ -package dto; - -import java.io.Serializable; - -//interface for the scan objects - -public interface ScanInterface extends Serializable{ - public String constructPayload(); -} \ No newline at end of file diff --git a/src/main/java/dto/ScanObj.java b/src/main/java/dto/ScanObj.java deleted file mode 100644 index fe0821e..0000000 --- a/src/main/java/dto/ScanObj.java +++ /dev/null @@ -1,28 +0,0 @@ -package dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.ToString; -import lombok.extern.jackson.Jacksonized; -import java.io.Serializable; - -import java.io.Serializable; - -@AllArgsConstructor -@Builder -@Getter -@ToString -@Jacksonized -public class ScanObj implements Serializable { - - public static final String SQL = "INSERT INTO scans " + - "(scan_id, offering_id, event_id, is_managed_service, component_list) " + - "VALUES (? ? ? ? ?)"; - - private final String scanId; - private final String productId; - private final String eventId; - private final String isManagedService; - private final String componentList; -} \ No newline at end of file diff --git a/src/main/java/dto/ScanObjPayload.java b/src/main/java/dto/ScanObjPayload.java deleted file mode 100644 index a914cc4..0000000 --- a/src/main/java/dto/ScanObjPayload.java +++ /dev/null @@ -1,17 +0,0 @@ -package dto; - -import org.json.JSONException; -import org.json.JSONObject; - -public class ScanObjPayload { - public static ScanObj constructScanPayload(JSONObject jsonObj) throws JSONException { - return new ScanObj( - jsonObj.getString("scan_id"), - jsonObj.getString("offering_id"), - jsonObj.getString("event_id"), - jsonObj.getString("is_managed_service"), - jsonObj.getString("component_list")); - } - - private ScanObjPayload() {} -} diff --git a/src/main/java/rest/CreateGetResource.java b/src/main/java/rest/CreateGetResource.java deleted file mode 100644 index 1e3f820..0000000 --- a/src/main/java/rest/CreateGetResource.java +++ /dev/null @@ -1,61 +0,0 @@ -package rest; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Set; - -import dto.ScanObj; -import dto.ConnectDB; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import io.quarkus.security.Authenticated; - -// @Path("/api/v1/[osh-scan]") -@Path("/scanGet") -@Authenticated -public class CreateGetResource { - - private static final Logger logger = LoggerFactory.getLogger(CreateGetResource.class); - - CreateScanService createScanService; - - private Set Scans = Collections.newSetFromMap(Collections.synchronizedMap(new LinkedHashMap<>())); - - public CreateGetResource() { - // LDB: @TODO either put some code here or remove this not used public constructor - } - - @GET - @Path("/{scanId}") - public Set list(@PathParam("scanId") String scanId) { - //use to return specific scanIds just use usual fetch from sets, will be querying hte db directly here - ConnectDB connectDB = new ConnectDB(); - String sql = "SELECT * FROM scans WHERE scan_id=?"; - try(Connection conn = connectDB.connect(); - PreparedStatement pstmt = conn.prepareStatement(sql)) { - pstmt.setString(1, scanId); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) { - //very ugly solution needs some change to where we put the query - Scans.add(new ScanObj( - rs.getString("scan_id"), - rs.getString("offering_id"), - rs.getString("event_id"), - rs.getString("is_managed_service"), - rs.getString("component_list"))); - } - } catch (SQLException e) { - logger.error(e.getMessage()); - } - return Scans; - } -} diff --git a/src/main/java/rest/CreateScanRequest.java b/src/main/java/rest/CreateScanRequest.java deleted file mode 100644 index 4e2f346..0000000 --- a/src/main/java/rest/CreateScanRequest.java +++ /dev/null @@ -1,107 +0,0 @@ -package rest; - -import dto.BrewObj; -import dto.ConnectDB; -import dto.BrewObjPayload; -import dto.GitObj; -import dto.GitObjPayload; -import dto.PncObj; -import dto.PncObjPayload; - -import org.eclipse.microprofile.rest.client.inject.RestClient; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URISyntaxException; -import io.quarkus.security.Authenticated; - -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -@Authenticated -@Path("/scanRequest") -public class CreateScanRequest { - - private static final Logger logger = LoggerFactory.getLogger(CreateScanRequest.class); - - @RestClient - CreateScanService createScanService; - GreetingResource greetingResource; - - @POST - @Path("/brew") - @Consumes({ "application/json" }) - // in theory should take List to clean it up - public BrewObj invokeBrewScanAnalyze(@Valid String scanInvocation) throws JSONException { - JSONObject jsonData = new JSONObject(scanInvocation); - BrewObj brewObj = BrewObjPayload.constructScanPayload(jsonData); - ConnectDB connectDB = new ConnectDB(); - try(Connection conn = connectDB.connect(); - PreparedStatement pstmt = conn.prepareStatement(BrewObj.SQL)) { - pstmt.setString(1, brewObj.getBuildSystemType()); - pstmt.setString(2, brewObj.getBrewId()); - pstmt.setString(3, brewObj.getBrewNvr()); - pstmt.setString(4, brewObj.getPncId()); - pstmt.setString(5, brewObj.getArtifactType()); - pstmt.setString(6, brewObj.getFileName()); - pstmt.setBoolean(7, brewObj.getBuiltFromSource()); - pstmt.executeUpdate(); - } catch (SQLException e) { - logger.error(e.getMessage()); - } - greetingResource.invokeScanTask(brewObj.getBrewNvr()); - return brewObj; - } - - @POST - @Path("/git") - @Consumes({ "application/json" }) - public void invokeGitScanAnalyze(@Valid String scanInvocation)throws URISyntaxException { - throw new UnsupportedOperationException("unImplemented fucntionality"); - - // JSONObject jsonData = new JSONObject(scanInvocation); - // GitObj gitObj = GitObjPayload.constructScanPayload(jsonData); - - // ConnectDB connectDB = new ConnectDB(); - // Connection conn = connectDB.connect(); - // Statement stmt = null; - // String sql = "INSERT INTO gitscans (buildsystemtype, repository, reference, commitid) VALUES ('"+gitObj.buildSystemType+"','"+gitObj.repository+"','"+gitObj.reference+"','"+gitObj.commitId+"')"; - // try{ - // stmt = conn.createStatement(); - // ResultSet rs = stmt.executeQuery(sql); - // conn.close(); - // } catch (SQLException e){ - // System.out.println(e); - // } - // return gitObj; - } - - @POST - @Path("/pnc") - @Consumes({ "application/json" }) - public void invokePncScanAnalyze(@Valid String scanInvocation)throws URISyntaxException { - throw new UnsupportedOperationException("unImplemented fucntionality"); - // JSONObject jsonData = new JSONObject(scanInvocation); - // PncObj pncObj = PncObjPayload.constructScanPayload(jsonData); - - // ConnectDB connectDB = new ConnectDB(); - // Connection conn = connectDB.connect(); - // Statement stmt = null; - // String sql = "INSERT INTO pncscans (buildsystemtype, buildid) VALUES ('"+pncObj.buildSystemType+"','"+pncObj.buildId+"')"; - // try{ - // stmt = conn.createStatement(); - // ResultSet rs = stmt.executeQuery(sql); - // conn.close(); - // } catch (SQLException e){ - // System.out.println(e); - // } - // return pncObj; - } -} diff --git a/src/main/java/rest/CreateScanResource.java b/src/main/java/rest/CreateScanResource.java deleted file mode 100644 index 5602898..0000000 --- a/src/main/java/rest/CreateScanResource.java +++ /dev/null @@ -1,53 +0,0 @@ -package rest; - -import dto.ConnectDB; -import dto.ScanObjPayload; -import dto.ScanObj; -import dto.ScanObjPayload; -import org.eclipse.microprofile.rest.client.inject.RestClient; -import org.json.JSONObject; - -import org.eclipse.microprofile.rest.client.inject.RestClient; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.net.URISyntaxException; -import io.quarkus.security.Authenticated; -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -@Path("/") -public class CreateScanResource { - - private static final Logger logger = LoggerFactory.getLogger(CreateScanResource.class); - - @RestClient - CreateScanService createScanService; - - @POST - @Consumes({ "application/json" }) - //in theory should take List to clean it up - public void invokeScanAnalyze(@Valid String scanInvocation) throws URISyntaxException { - throw new UnsupportedOperationException("unImplemented fucntionality"); - // JSONObject jsonData = new JSONObject(scanInvocation); - // ScanObj scanObj = ScanObjPayload.constructScanPayload(jsonData); - // ConnectDB connectDB = new ConnectDB(); - // Connection conn = connectDB.connect(); - // Statement stmt = null; - // String sql = "INSERT INTO scans (scanid, productid, eventid, ismanagedservice, componentlist) VALUES ('" +scanObj.scanId+"', '"+scanObj.productId+"', '"+scanObj.eventId+"', '"+scanObj.isManagedService+"', '"+scanObj.componentList+"')"; - // try{ - // stmt = conn.createStatement(); - // ResultSet rs = stmt.executeQuery(sql); - // conn.close(); - // } catch (SQLException e){ - // System.out.println(e); - // } - // return scanObj; - } -} diff --git a/src/main/java/rest/CreateScanService.java b/src/main/java/rest/CreateScanService.java deleted file mode 100644 index 30b85d4..0000000 --- a/src/main/java/rest/CreateScanService.java +++ /dev/null @@ -1,16 +0,0 @@ -package rest; - -import dto.ScanObj; -import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; - -import javax.ws.rs.POST; -import javax.ws.rs.Path; - -@Path("/") -@RegisterRestClient -public interface CreateScanService { - //should be used for fixing the incoming data from post requests but not yet implemented - @POST - ScanObj invokeScanAnalysis(ScanObj scanObj); - -} diff --git a/src/main/java/rest/CreateStartScan.java b/src/main/java/rest/CreateStartScan.java deleted file mode 100644 index 26c5342..0000000 --- a/src/main/java/rest/CreateStartScan.java +++ /dev/null @@ -1,68 +0,0 @@ -package rest; - -import dto.ConnectDB; -import dto.ScanObj; -import io.quarkus.security.Authenticated; -import org.eclipse.microprofile.rest.client.inject.RestClient; - -import java.net.URISyntaxException; -import io.quarkus.security.Authenticated; - -import org.eclipse.microprofile.rest.client.inject.RestClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.Path; -import javax.ws.rs.PUT; -import javax.ws.rs.PathParam; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -@Authenticated -@Path("/startScan") -public class CreateStartScan { - - private static final Logger logger = LoggerFactory.getLogger(CreateStartScan.class); - - @RestClient - CreateScanService createScanService; - GreetingResource greetingResource; - - @PUT - @Path("/{scanId}") - public void invokeScanAnalyze(@PathParam("scanId") String scanId) throws URISyntaxException { - throw new UnsupportedOperationException("unImplemented fucntionality"); - // ConnectDB connectDB = new ConnectDB(); - // Connection conn = connectDB.connect(); - // //this is ugly needs to berewritten - // Statement stmt = null; - // ScanObj finalScan = null; - - // String sql = "SELECT * FROM scans WHERE scanid=" + scanId; - // //need to add figure out an archieve system and wether its nessacery (archieve value??) - // try{ - // stmt = conn.createStatement(); - // //terrible solution has to be a better way of doing this - // ResultSet rs = stmt.executeQuery(sql); - - // //fix for individual results (not resultset) - // //TODO: need to add unique keys to DBs - // finalScan = new ScanObj(rs.getString("scanid"),rs.getString("productid"),rs.getString("eventid"),rs.getString("ismanagedservice"),rs.getString("componentlist")); - // String copySql = "INSERT INTO archive (scanid, productid, eventid, ismanagedservice, componentlist) VALUES ('" +finalScan.scanId+"', '"+finalScan.productId+"', '"+finalScan.eventId+"', '"+finalScan.isManagedService+"', '"+finalScan.componentList+"')"; - // stmt.executeUpdate(copySql); - - // //TODO add proper checks - // String deleteSql = "DELETE FROM scans WHERE scanid=" + scanId; - // stmt.executeUpdate(deleteSql); - - // //send task to the actual interface here using the resultset returned (should multiple scanids be allowed): - // //once the task is complete AND we have confirmation that the scan is done run the following sql - // conn.close(); - // } catch (SQLException e){ - // System.out.println(e); - // } - // return finalScan; - } -} diff --git a/src/main/java/rest/GreetingResource.java b/src/main/java/rest/GreetingResource.java deleted file mode 100644 index bf64094..0000000 --- a/src/main/java/rest/GreetingResource.java +++ /dev/null @@ -1,68 +0,0 @@ -package rest; - -import javax.inject.Inject; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.core.MediaType; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.RandomStringUtils; - -import io.fabric8.tekton.client.TektonClient; -import io.fabric8.tekton.pipeline.v1beta1.ArrayOrString; -import io.fabric8.tekton.pipeline.v1beta1.Param; -import io.fabric8.tekton.pipeline.v1beta1.TaskRun; -import io.fabric8.tekton.pipeline.v1beta1.TaskRunBuilder; - -public class GreetingResource { - - public static final String NAMESPACE = "pct-security-tooling"; - public static final String BUILD_ID = "buildId"; - public static final String SCAN_PROFILE = "scanProfile"; - public static final String TASK_REFERENCE = "osh-scan-task"; - public static final String SERVICE_ACCOUNT = "osh-wrapper-client-sa"; - - @Inject - TektonClient tektonClient; - - public String listPipelines() { - - List pipelineList = new ArrayList<>(); - - tektonClient.v1beta1().pipelines() - .inNamespace(NAMESPACE) - .list() - .getItems() - .forEach(p -> pipelineList.add(p.getMetadata().getName())); - - return pipelineList.toString(); - } - - public String invokeScanTask(String buildId) { - // String buildId = "xterm-366-8.el9"; - String scanProfile = "snyk-only-unstable"; - - // random taskrun name generating for now - TaskRun taskRun = new TaskRunBuilder().withNewMetadata().withName("osh-scan-taskrun-" + RandomStringUtils.randomAlphanumeric(8).toLowerCase()) - .endMetadata() - .withNewSpec() - .withServiceAccountName(SERVICE_ACCOUNT) - .withNewTaskRef() - .withName(TASK_REFERENCE) - .endTaskRef() - .withParams( - new Param("buildId", new ArrayOrString(buildId)), - new Param("scanProfile", new ArrayOrString(scanProfile))) - .endSpec() - .build(); - - tektonClient.v1beta1().taskRuns().inNamespace(NAMESPACE).resource(taskRun).create(); - - - return "Scan invoked"; - } - -} diff --git a/src/main/java/rest/RemoveScan.java b/src/main/java/rest/RemoveScan.java deleted file mode 100644 index 783873c..0000000 --- a/src/main/java/rest/RemoveScan.java +++ /dev/null @@ -1,43 +0,0 @@ -package rest; - -import dto.ConnectDB; - -import org.eclipse.microprofile.rest.client.inject.RestClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.Path; -import javax.ws.rs.DELETE; -import javax.ws.rs.PathParam; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -@Path("/deleteScan") -public class RemoveScan { - - private static final Logger logger = LoggerFactory.getLogger(RemoveScan.class); - - // @Inject - @RestClient - CreateScanService createScanService; - - @DELETE - @Path("/{scanId}") - public boolean invokeScanAnalyze(@PathParam("scanId") String scanId) { - boolean rc = false; - //send task to the actual interface here using the resultset returned (should multiple scanids be allowed): - //once the task is complete AND we have confirmation that the scan is done run the following sql - String qry = "DELETE FROM scans WHERE scan_id=?"; - ConnectDB connectDB = new ConnectDB(); - try(Connection conn = connectDB.connect(); - PreparedStatement pstmt = conn.prepareStatement(qry)) { - pstmt.setString(1, scanId); - pstmt.executeUpdate(); - rc = true; - } catch (SQLException e) { - logger.error(e.getMessage()); - } - return rc; - } -} diff --git a/src/main/java/rest/Scan.java b/src/main/java/rest/Scan.java deleted file mode 100644 index e7e84b4..0000000 --- a/src/main/java/rest/Scan.java +++ /dev/null @@ -1,41 +0,0 @@ -package rest; - -public class Scan { - private int scanId; - private String productId; - private String eventId; - private String isManagedService; - private String componentList; - - public int getScanId() { - return scanId; - } - public void setScanId(int scanId) { - this.scanId = scanId; - } - public String getProductId() { - return productId; - } - public void setProductId(String productId) { - this.productId = productId; - } - public String getEventId() { - return eventId; - } - public void setEventId(String eventId) { - this.eventId = eventId; - } - public String getIsManagedService(){ - return isManagedService; - } - public void setIsManagedService(String isManagedService){ - this.isManagedService = isManagedService; - } - public String getComponentList(){ - return componentList; - } - public void setComponentList(String componentList){ - this.componentList = componentList; - } - -} \ No newline at end of file diff --git a/src/main/java/rest/StoreData.java b/src/main/java/rest/StoreData.java deleted file mode 100644 index 639ba8d..0000000 --- a/src/main/java/rest/StoreData.java +++ /dev/null @@ -1,52 +0,0 @@ -// package rest; - - -// import dto.ConnectDB; -// import dto.Scan; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; - // import org.hibernate.EntityManager; - - -// @Path("/storeData") -// public class StoreData { - -// //all of these need cleaning up to be a more sensible soution -// // @RestClient -// // CreateScanService createScanService; - -// @GET -// public void Store() { - -// //Create typesafe ServiceRegistry object -// StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); - -// Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build(); - -// SessionFactory factory = meta.getSessionFactoryBuilder().build(); -// Session session = factory.openSession(); -// Transaction t = session.beginTransaction(); -// Scan e1=new Scan(); -// e1.setScanId(2); -// e1.setProductId("1"); -// e1.setEventId("Chawla"); -// e1.setIsManagedService("aa"); -// e1.setComponentList("aaa"); - -// session.save(e1); -// t.commit(); -// System.out.println("successfully saved"); -// factory.close(); -// session.close(); - -// } -// } \ No newline at end of file diff --git a/src/main/java/rest/TektonResourceClient.java b/src/main/java/rest/TektonResourceClient.java deleted file mode 100644 index 5db3239..0000000 --- a/src/main/java/rest/TektonResourceClient.java +++ /dev/null @@ -1,20 +0,0 @@ -// package rest; - -// import java.util.List; - -// import jakarta.enterprise.context.ApplicationScoped; -// import io.fabric8.tekton.client.TektonClient; -// import io.fabric8.tekton.pipeline.v1beta1.Pipeline; - - -// @ApplicationScoped -// public class TektonResourceClient { - -// // @Inject -// TektonClient tektonClient;l - -// public List listPipelines() { -// return tektonClient.v1beta1().pipelines().list().getItems(); -// } - -// } \ No newline at end of file diff --git a/src/main/java/rest/TektonTaskCreate.java b/src/main/java/rest/TektonTaskCreate.java deleted file mode 100644 index 651e917..0000000 --- a/src/main/java/rest/TektonTaskCreate.java +++ /dev/null @@ -1,165 +0,0 @@ -// package rest; - -import javax.inject.Inject; -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import org.json.JSONObject; -import org.json.JSONArray; -import dto.ScanObj; -import dto.BrewObj; -import dto.ConnectDB; -import dto.ScanObjPayload; -import dto.BrewObjPayload; -import dto.GitObj; -import dto.GitObjPayload; -import dto.PncObj; -import dto.PncObjPayload; - -import static constants.HttpHeaders.AUTHORIZATION_STRING; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Set; -import dto.ScanObj; -import dto.ConnectDB; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; - -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.inject.Inject; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import java.util.Set; -import java.util.stream.Collectors; -import javax.inject.Inject; -import javax.ws.rs.Consumes; - -import java.sql.*; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -// import org.hibernate.EntityManager; -import jakarta.persistence.EntityManager; -import jakarta.persistence.Cacheable; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.NamedQuery; -import jakarta.persistence.QueryHint; -import jakarta.persistence.SequenceGenerator; -import jakarta.persistence.Table; - -import org.eclipse.microprofile.rest.client.inject.RestClient; -import dto.ScanObj; - -import javax.inject.Inject; -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import org.json.JSONObject; -import org.json.JSONArray; -import dto.ScanObj; -import dto.BrewObj; -import dto.ConnectDB; -import dto.ScanObjPayload; -import dto.BrewObjPayload; -import dto.GitObj; -import dto.GitObjPayload; -import dto.PncObj; -import dto.PncObjPayload; - -import static constants.HttpHeaders.AUTHORIZATION_STRING; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; - -import io.fabric8.tekton.client.DefaultTektonClient; -import io.fabric8.tekton.client.TektonClient; -import io.fabric8.tekton.pipeline.v1beta1.TaskBuilder; -import io.fabric8.tekton.pipeline.v1beta1.TaskRunBuilder; -import io.fabric8.tekton.pipeline.v1beta1.Task; - - -@Path("/tekton") -public class TektonTaskCreate { - - @RestClient - - private static final String NAMESPACE = "default"; - - @POST - @Consumes({ "application/json" }) - public void invokeTektonTask(String data) { - JSONObject jsonData = new JSONObject(data); - // ScanObj scanObj = ScanObjPayload.constructScanPayload(jsonData); - - //dont leave this in live needs to be adjusted (currently would cause a ton of issues) - String tektonArgs = "osh-cli mock-build --config="+jsonData.get("config")+"--brew-build"+jsonData.get("nvr"); - - try (TektonClient tkn = new DefaultTektonClient()) { - // Create Task - tkn.v1beta1().tasks().inNamespace(NAMESPACE).resource(new TaskBuilder() - .withNewMetadata().withName("tekton-osh-client").endMetadata() - .withNewSpec() - .addNewStep() - .withName("osh-client") - .withImage("alpine:3.12") - .withCommand("osh-cli") - .withArgs(tektonArgs) - .endStep() - .endSpec() - .build()).createOrReplace(); - - // Create TaskRun - tkn.v1beta1().taskRuns().inNamespace(NAMESPACE).resource(new TaskRunBuilder() - .withNewMetadata().withName("tekton-osh-client-task-run").endMetadata() - .withNewSpec() - .withNewTaskRef() - .withName("tekton-osh-client") - .endTaskRef() - .endSpec() - .build()).createOrReplace(); - } - } -} \ No newline at end of file diff --git a/src/main/java/rest/callTekton.java b/src/main/java/rest/callTekton.java deleted file mode 100644 index 1f4f518..0000000 --- a/src/main/java/rest/callTekton.java +++ /dev/null @@ -1,116 +0,0 @@ -// package rest; - - -// import io.fabric8.tekton.client.DefaultTektonClient; -// import io.fabric8.tekton.client.TektonClient; - - -// import javax.inject.Inject; -// import javax.validation.Valid; -// import javax.ws.rs.Consumes; -// import javax.ws.rs.POST; -// import javax.ws.rs.Path; -// import java.net.URI; -// import java.net.URISyntaxException; -// import java.util.ArrayList; -// import java.util.Arrays; -// import java.util.List; -// import java.util.UUID; -// import org.json.JSONObject; -// import org.json.JSONArray; -// import dto.ScanObj; -// import dto.BrewObj; -// import dto.ConnectDB; -// import dto.ScanObjPayload; -// import dto.BrewObjPayload; -// import dto.GitObj; -// import dto.GitObjPayload; -// import dto.PncObj; -// import dto.PncObjPayload; - -// import static constants.HttpHeaders.AUTHORIZATION_STRING; -// import java.sql.Connection; -// import java.sql.DriverManager; -// import java.sql.SQLException; - -// import java.sql.Connection; -// import java.sql.DriverManager; -// import java.sql.ResultSet; -// import java.sql.Statement; - -// import java.util.Collections; -// import java.util.LinkedHashMap; -// import java.util.Set; -// import dto.ScanObj; -// import dto.ConnectDB; - -// import java.sql.Connection; -// import java.sql.DriverManager; -// import java.sql.SQLException; - -// import java.sql.Connection; -// import java.sql.DriverManager; -// import java.sql.ResultSet; -// import java.sql.Statement; - -// import javax.ws.rs.DELETE; -// import javax.ws.rs.GET; -// import javax.ws.rs.POST; -// import javax.ws.rs.Path; -// import javax.inject.Inject; -// import javax.ws.rs.GET; -// import javax.ws.rs.Path; -// import javax.ws.rs.PathParam; -// import java.util.Set; -// import java.util.stream.Collectors; -// import javax.inject.Inject; -// import javax.ws.rs.Consumes; - -// import java.sql.*; - -// import com.fasterxml.jackson.databind.ObjectMapper; -// import com.fasterxml.jackson.databind.ObjectWriter; - -// // import org.hibernate.EntityManager; -// import jakarta.persistence.EntityManager; -// import jakarta.persistence.Cacheable; -// import jakarta.persistence.Column; -// import jakarta.persistence.Entity; -// import jakarta.persistence.GeneratedValue; -// import jakarta.persistence.Id; -// import jakarta.persistence.NamedQuery; -// import jakarta.persistence.QueryHint; -// import jakarta.persistence.SequenceGenerator; -// import jakarta.persistence.Table; - - -// import io.fabric8.tekton.client.DefaultTektonClient; -// import io.fabric8.tekton.client.TektonClient; -// import io.fabric8.tekton.pipeline.v1beta1.TaskBuilder; -// import io.fabric8.tekton.pipeline.v1beta1.Task; - -// public class callTekton { - -// private static final String NAMESPACE = "default"; - -// public static void main(String[] args) { -// try (TektonClient tkn = new DefaultTektonClient()) { -// // Load Task object from YAML -// Task task = tkn.v1beta1() -// .tasks() -// .load(callTekton.class.getResourceAsStream("../resources/baseScan.yml")).get(); - -// // Create Task object into Kubernetes -// tkn.v1beta1().tasks().inNamespace(NAMESPACE).createOrReplace(task); - -// // Get Task object from APIServer -// String taskName = task.getMetadata().getName(); -// task = tkn.v1beta1().tasks().inNamespace(NAMESPACE) -// .withName(taskName) -// .get(); - -// // Delete Task object -// tkn.v1beta1().tasks().inNamespace(NAMESPACE).withName(taskName).delete(); -// } -// } -// } \ No newline at end of file diff --git a/src/main/resources/META-INF/resources/index.html b/src/main/resources/META-INF/resources/index.html new file mode 100644 index 0000000..bb7a80f --- /dev/null +++ b/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,288 @@ + + + + + osh-wrapper-service - 1.0.0-SNAPSHOT + + + +
+
+
+ + + + + quarkus_logo_horizontal_rgb_1280px_reverse + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+
+

You just made a Quarkus application.

+

This page is served by Quarkus.

+ Visit the Dev UI +

This page: src/main/resources/META-INF/resources/index.html

+

App configuration: src/main/resources/application.properties

+

Static assets: src/main/resources/META-INF/resources/

+

Code: src/main/java

+

Dev UI V1: /q/dev-v1

+

Generated starter code:

+
    +
  • + RESTEasy Reactive Easily start your Reactive RESTful Web Services +
    @Path: /hello +
    Related guide +
  • + +
+
+
+

Selected extensions

+
    +
  • Kerberos
  • +
  • RESTEasy Reactive (guide)
  • +
  • OpenShift (guide)
  • +
  • Tekton Client
  • +
+
Documentation
+

Practical step-by-step guides to help you achieve a specific goal. Use them to help get your work + done.

+
Set up your IDE
+

Everyone has a favorite IDE they like to use to code. Learn how to configure yours to maximize your + Quarkus productivity.

+
+
+
+ + diff --git a/src/main/resources/Scan.hbm.xml b/src/main/resources/Scan.hbm.xml deleted file mode 100644 index 73cd545..0000000 --- a/src/main/resources/Scan.hbm.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index c54769a..a2748bb 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -21,9 +21,34 @@ #%dev.quarkus.kerberos.keytab-path= HTTP_osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com@IPA.REDHAT.COM.keytab #%dev.quarkus.kerberos.service-principal-name= HTTP/osh-pct-security-tooling.apps.ocp-c1.prod.psi.redhat.com@IPA.REDHAT.COM +########################################## +# Data Source # +########################################## +%dev.quarkus.datasource.devservices.enabled=true +%dev.quarkus.datasource.db-kind = postgresql +%dev.quarkus.datasource.username = quarkus +%dev.quarkus.datasource.password = quarkus +#%dev.quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db +%dev.quarkus.hibernate-orm.database.generation=drop-and-create + +%stage.quarkus.kubernetes-config.secrets.enabled=true +quarkus.kubernetes-config.secrets=postgresql +%stage.quarkus.datasource.jdbc.url=jdbc:postgresql://postgresql:5432/${database-name} +%stage.quarkus.datasource.username=${database-user} +%stage.quarkus.datasource.password=${database-password} +%stage.quarkus.hibernate-orm.database.generation=drop-and-create + + +#Always provide swagger ui +quarkus.swagger-ui.always-include=true +%dev.quarkus.openshift.service-account=osh-wrapper-client-sa +%dev.quarkus.openshift.namespace=pct-security-tooling + %stage.quarkus.openshift.name=osh +quarkus.openshift.service-account=osh-wrapper-client-sa %stage.quarkus.openshift.labels.env=stage %stage.quarkus.log.level=DEBUG +quarkus.arc.remove-unused-beans=false #Only in Quarkus > 3.x %stage.quarkus.openshift.route.tls.termination=edge @@ -31,7 +56,7 @@ %stage.quarkus.openshift.route.expose=false %stage.quarkus.openshift.route.target-port=https %stage.quarkus.openshift.route.tls.insecure-edge-termination-policy=redirect - +%stage.quarkus.openshift.namespace=pct-security-tooling ########################################## # Kerberos Specifics # @@ -48,5 +73,12 @@ %stage.quarkus.openshift.config-map-volumes.osh-wrapper-config-vol.items."linux-krb5.conf".path=linux-krb5.conf %stage.quarkus.openshift.mounts.osh-wrapper-config-vol.read-only=true +########################################## +# Tekton Specifics (Used in app) # +########################################## +tekton.pipeline.ref=osh-client-from-source +tekton.task.ref=osh-scan-task +tekton.service-account=${quarkus.openshift.service-account} + diff --git a/src/main/resources/baseScan.yml b/src/main/resources/baseScan.yml deleted file mode 100644 index 03f413e..0000000 --- a/src/main/resources/baseScan.yml +++ /dev/null @@ -1,16 +0,0 @@ -apiVersion: tekton.dev/v1beta1 -kind: Task -metadata: - name: basescan -spec: - params: - - name: buildId - type: string - - name: config - type: string - steps: - - name: baseScan - image: openshift - script: | - #!/bin/bash - osh-cli mock-build --config=params.config --brew-build params.buildId \ No newline at end of file diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml deleted file mode 100644 index f3621dc..0000000 --- a/src/main/resources/hibernate.cfg.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - update - org.hibernate.dialect.PostgreSQLDialect - org.postgresql.Driver - jdbc:postgresql://localhost:5432/mydb - postgres - password - - true - true - - - - \ No newline at end of file diff --git a/src/test/java/com/redhat/pctsec/model/osh/paramMapperTest.java b/src/test/java/com/redhat/pctsec/model/osh/paramMapperTest.java new file mode 100644 index 0000000..f24ee8c --- /dev/null +++ b/src/test/java/com/redhat/pctsec/model/osh/paramMapperTest.java @@ -0,0 +1,22 @@ +package com.redhat.pctsec.model.osh; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import java.lang.String; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +@QuarkusTest +public class paramMapperTest { + + + + @Test + public void testSnykScan() { + paramMapper pm = new paramMapper("-p snyk-only-unstable --tarball-build-script=\":\""); + System.out.println(pm); + } + +} \ No newline at end of file diff --git a/src/test/java/dto/TestPayload.java b/src/test/java/dto/TestPayload.java deleted file mode 100644 index 51980ac..0000000 --- a/src/test/java/dto/TestPayload.java +++ /dev/null @@ -1,107 +0,0 @@ -package dto; - -import org.json.JSONObject; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import static org.junit.jupiter.api.Assertions.*; - -class TestPayload { - - private static final Logger logger = LoggerFactory.getLogger(TestPayload.class); - - @Test - void TestBrew() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("build_system_type", "brew"); - jsonObject.put("brew_id", "1"); - jsonObject.put("brew_nvr", "1.1.0"); - jsonObject.put("pnc_id", "153"); - jsonObject.put("artifact_type", "arti"); - jsonObject.put("file_name", "myfile"); - jsonObject.put("built_from_source", true); - - BrewObj brewObj1 = BrewObjPayload.constructScanPayload(jsonObject); - BrewObj brewObj2 = new BrewObj( - jsonObject.getString("build_system_type"), - jsonObject.getString("brew_id"), - jsonObject.getString("brew_nvr"), - jsonObject.getString("pnc_id"), - jsonObject.getString("artifact_type"), - jsonObject.getString("file_name"), - jsonObject.getBoolean("built_from_source")); - - logger.info("BrewObj1: " + brewObj1.toString()); - logger.info("BrewObj2: " + brewObj2.toString()); - assertEquals(brewObj1.getBuildSystemType(), brewObj2.getBuildSystemType()); - assertEquals(brewObj1.getBrewId(), brewObj2.getBrewId()); - assertEquals(brewObj1.getBrewNvr(), brewObj2.getBrewNvr()); - assertEquals(brewObj1.getPncId(), brewObj2.getPncId()); - assertEquals(brewObj1.getArtifactType(), brewObj2.getArtifactType()); - assertEquals(brewObj1.getFileName(), brewObj2.getFileName()); - assert(brewObj1.getBuiltFromSource() == brewObj2.getBuiltFromSource()); - } - - @Test - void TestGit() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("build_system_type", "git"); - jsonObject.put("repository", "repo"); - jsonObject.put("reference", "ref"); - jsonObject.put("commit_id", "c6385a754421a57cd0a26ccba187cd687c8d1258"); - - GitObj gitObj1 = GitObjPayload.constructScanPayload(jsonObject); - GitObj gitObj2 = new GitObj( - jsonObject.getString("build_system_type"), - jsonObject.getString("repository"), - jsonObject.getString("reference"), - jsonObject.getString("commit_id")); - logger.info("GitObj1: " + gitObj1.toString()); - logger.info("GitObj2: " + gitObj2.toString()); - assertEquals(gitObj1.getBuildSystemType(), gitObj2.getBuildSystemType()); - assertEquals(gitObj1.getRepository(), gitObj2.getRepository()); - assertEquals(gitObj1.getReference(), gitObj2.getReference()); - assertEquals(gitObj1.getCommitId(), gitObj2.getCommitId()); - } - - @Test - void TestPnc() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("build_system_type", "pnc"); - jsonObject.put("build_id", "153"); - - PncObj pncObj1 = PncObjPayload.constructScanPayload(jsonObject); - PncObj pncObj2 = new PncObj( - jsonObject.getString("build_system_type"), - jsonObject.getString("build_id")); - logger.info("PncObj1: " + pncObj1.toString()); - logger.info("PncObj2: " + pncObj2.toString()); - assertEquals(pncObj1.getBuildSystemType(), pncObj2.getBuildSystemType()); - assertEquals(pncObj1.getBuildId(), pncObj2.getBuildId()); - } - - @Test - void TestScan() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("scan_id", "ABC"); - jsonObject.put("offering_id", "product#"); - jsonObject.put("event_id", "event#"); - jsonObject.put("is_managed_service", "TRUE"); - jsonObject.put("component_list", "components"); - - ScanObj scanObj1 = ScanObjPayload.constructScanPayload(jsonObject); - ScanObj scanObj2 = new ScanObj( - jsonObject.getString("scan_id"), - jsonObject.getString("offering_id"), - jsonObject.getString("event_id"), - jsonObject.getString("is_managed_service"), - jsonObject.getString("component_list")); - logger.info("ScanObj1: " + scanObj1.toString()); - logger.info("ScanObj2: " + scanObj2.toString()); - assertEquals(scanObj1.getScanId(), scanObj2.getScanId()); - assertEquals(scanObj1.getProductId(), scanObj2.getProductId()); - assertEquals(scanObj1.getEventId(), scanObj2.getEventId()); - assertEquals(scanObj1.getIsManagedService(), scanObj2.getIsManagedService()); - assertEquals(scanObj1.getComponentList(), scanObj2.getComponentList()); - } -}