본문으로 건너뛰기
버전: 2504.1
  • Sparrow On-Demand Node SDK는 Typescript를 지원합니다.

요구사항

  • Node.js 20 이상
    Active LTS 혹은 Maintenance LTS releases를 사용해야 합니다. 자세한 내용은 Node.js Release를 참고해주세요.

개발 환경 설정

  • Yarn
    Yarn을 통해 sdk를 설치할 수 있습니다.

    yarn add 'sparrow-ondemand-node-sdk:{latest version}'
  • 로컬 .tgz 사용
    로컬에 위치한 .tgz 파일을 사용하려면 아래와 같이 설치를 진행합니다.

    yarn add ./sparrow-ondemand-node-sdk-2504.1.tgz

토큰 발급


초기화

ondemand 분석 관련 요청을 위해 아래의 코드를 추가해 OndemandClient 인스턴스를 생성합니다.

import {
OndemandClient,
OndemandClientConfig
} from "sparrow-ondemand-node-sdk"

// config
const config = new OndemandClientConfig({apiKey : 발급 받은 토큰});

// create client
const OndemandClient = new OndemandClient(config);

OndemandClientConfig 는 OndemandClient 생성시 설정 값 지정을 위해 사용됩니다.

  • apiKey : api 요청시 인증을 위해 3에서 발급 받은 토큰 입력

분석 메소드

생성한 client의 메소드를 통해 분석을 수행합니다. 메소드 동작시 OndemandException이 발생 할 수 있습니다. 예외에 대한 자세한 내용은 아래를 참고해주세요

1. 분석 요청

생성한 client로 분석 요청을 전송할 수 있습니다.

import { ScanResponse } from 'sparrow-ondemand-node-sdk';

const scanResponse: ScanResponse = await client.doAnalysis(analysisRequest);

파라미터

  • analysisRequest 필수 object
    분석 요청 정보를 담는 객체이며, 각 분석 타입 별로 analysisRequest를 생성 할 수 있는 getSastAnalysisRequest, getScaAnalysisRequest, getDastAnalysisRequest 함수를 제공합니다.

    • getSastAnalysisRequest
      analysisSource, options를 인자로 전달해 SastAnalysisRequest를 생성합니다.

      import {
      getSastAnalysisRequest,
      SastOption
      } from "sparrow-ondemand-node-sdk"

      const sastAnalysisRequest = getSastAnalysisRequest({
      analysisSource: ...,
      options : [new SastOption(...), ...]
      })
      • analysisSource 필수 object
        분석할 파일이 저장된 저장소이며 VCS , ObjectStorage 타입을 지원합니다.

        • Vcs

          • url 필수 string
            분석할 파일이 저장된 저장소의 url입니다.
          • branch string
            저장소 중 분석하려는 파일이 업로드된 브랜치의 이름입니다. 입력하지 않았을 때 default 브랜치를 타겟으로 분석합니다.
          • tag string
            분석하려는 브랜치의 태그 정보입니다.
          • commitId string
            분석 하려는 커밋 아이디 정보입니다.
          • id string
            VCS 인증을 위한 id입니다.
          • password string
            VCS 인증을 위한 password입니다. id와 같이 입력돼야 하며 authToken과 동시에 입력될 수 없습니다.
          • authToken string
            VCS 인증을 위한 authToken 이며 id, password와 동시에 입력될 수 없습니다.
        • ObjectStorage

          • bucket 필수 string
            분석할 파일의 bucket입니다.
          • object 필수 string
            분석할 파일의 object 경로입니다.
          • endPoint 필수 string
            분석할 버켓이 위치한 endPoint입니다.
          • accessKey string
            인증을 위한 accessKey입니다.
          • secretKey string
            인증을 위한 인증을 secretKey입니다.
      • options SastOption[ ]

        • SastOption object
          • key 필수 string
            Sast 분석 옵션 키
          • value 필수 any
            Sast 분석 옵션 value이며 디폴트 값이 존재합니다.
    • getScaAnalysisRequest
      analysisSource, options를 인자로 전달해 ScaAnalysisRequest를 생성합니다.

      import {
      getScaAnalysisRequest,
      ScaOption
      } from "sparrow-ondemand-node-sdk"

      const scaAnalysisRequest = getScaAnalysisRequest({
      analysisSource: ...,
      options : [new ScaOption(...), ...]
      })
      • analysisSource 필수 object
        분석할 파일이 저장된 저장소이며 VCS , ObjectStorage 타입을 지원합니다.

        • Vcs

          • url 필수 string
            분석할 파일이 저장된 저장소의 url입니다.
          • branch string
            저장소 중 분석하려는 파일이 업로드된 브랜치의 이름입니다. 입력하지 않았을 때 default 브랜치를 타겟으로 분석합니다.
          • tag string
            분석하려는 브랜치의 태그 정보입니다.
          • commitId string
            분석 하려는 커밋 아이디 정보입니다.
          • id string
            VCS 인증을 위한 id입니다.
          • password string
            VCS 인증을 위한 password입니다. id와 같이 입력돼야 하며 authToken과 동시에 입력될 수 없습니다.
          • authToken string
            VCS 인증을 위한 authToken 이며 id, password와 동시에 입력될 수 없습니다.
        • ObjectStorage

          • bucket 필수 string
            분석할 파일의 bucket입니다.
          • object 필수 string
            분석할 파일의 object 경로입니다.
          • endPoint 필수 string
            분석할 버켓이 위치한 endPoint입니다.
          • accessKey string
            인증을 위한 accessKey입니다.
          • secretKey string
            인증을 위한 인증을 secretKey입니다.
      • options ScaOption [ ]

        • ScaOption object
          • key 필수 string
            Sca 분석 옵션 키
          • value 필수 any
            Sca 분석 옵션 value
    • getDastAnalysisRequest
      analysisSource, options를 인자로 전달해 DastAnalysisRequest를 생성합니다.

      import {
      getDastAnalysisRequest,
      DastOption
      } from "sparrow-ondemand-node-sdk"

      const dastAnalysisRequest = getDastAnalysisRequest({
      targetUrl: "...",
      records: [...],
      options: [new DastOption(...), ...],
      })
      • targetUrl 필수 string
        웹 취약점 분석의 대상인 URL입니다.
      • records string[ ]
        웹 취약점 분석에 사용할 로그인 기록 파일 문자열입니다.
      • options DastOption[ ]
        • DastOptionobject
          • key 필수 string
            Dast 분석 옵션 키
          • value 필수 any
            Dast 분석 옵션 value

응답

  • ScanResponse object
    • requestId number
      분석 요청 id입니다.

예시 코드

Sast Vcs 분석 , Sca ObjectStorage 분석, Dast 분석을 요청하는 예시 코드입니다.

// Sast
import {
getSastAnalysisRequest,
VcsSource,
SastOption,
ScanResponse,
} from 'sparrow-ondemand-node-sdk';

const VcsSastAnalysisSource: VcsSource = {
type: 'Vcs',
source: {
url: 'gitUrl',
branch: 'branch',
tag: 'tag',
commitId: 'commitId',
id: 'id',
password: 'password',
authToken: 'authToken',
// id, password 또는 authToken만 설정
},
};

const sastOption = new SastOption('extensions', ['*']);

const sastAnalysisRequest = getSastAnalysisRequest({
analysisSource: VcsSastAnalysisSource,
options: [sastOption],
});

const scanResponse: ScanResponse = await client.doAnalysis(sastAnalysisRequest);

//Sca
import {
getScaAnalysisRequest,
ObjectStorageSource,
ScaOption,
ScanResponse,
} from 'sparrow-ondemand-node-sdk';

const ObjectStorageAnalysisSource: ObjectStorageSource = {
type: 'ObjectStorage',
source: {
bucket: 'bucket',
object: 'object',
endPoint: 'https://s3.ap-northeast-2.amazonaws.com',
accessKey: 'accessKey',
secretKey: 'secretKey',
},
};

const scaOption = new ScaOption('extensions', ['*']);

const scaAnalysisRequest = getScaAnalysisRequest({
analysisSource: ObjectStorageAnalysisSource,
options: [scaOption],
});

const scanResponse: ScanResponse = await client.doAnalysis(scaAnalysisRequest);

//Dast
import {
getDastAnalysisRequest,
DastOption,
ScanResponse,
} from 'sparrow-ondemand-node-sdk';

const dastOption = new DastOption('crawler.target.contain_entire_seed', true);

const dastRequest = getDastAnalysisRequest({
targetUrl: 'testURL',
records: ['record'],
options: [dastOption],
});

const scanResponse: ScanResponse = await client.doAnalysis(dastAnalysisRequest);

분석 도구 별로 생성한 AnalysisRequest를 파라미터로 doAnalysis 메소드를 호출합니다.
응답으로 ScanResponse의 requestId를 확인할 수 있습니다.


2. 분석 상태 확인

분석 요청이 정상적으로 됐다면 진행 중인 분석 상태를 확인 할 수 있습니다.

import { AnalysisStatus } from 'sparrow-ondemand-node-sdk';

const analysisStatus: AnalysisStatus =
await client.getAnalysisStatus(requestId);

파라미터

  • requestId 필수 number
    분석 요청 id입니다.

반환값

  • Analysis object
    • requestId number 분석 요청 id
    • index number
      요청 시 분석 인덱스
    • status string
      분석 상태
    • result string
      분석 상태
    • progress number
      분석 진행률
    • toolType string
      분석 타입
    • startTime string 분석 시작 시간
    • endTime string 분석 종료 시간
    • issueCount number
      분석에서 검출된 총 이슈의 수
    • issueCountRisk1 number
      위험도가 '낮음'에 해당하는 이슈 수
    • issueCountRisk2 number
      위험도가 '보통'에 해당하는 이슈 수
    • issueCountRisk3 number
      위험도가 '높음'에 해당하는 이슈 수
    • issueCountRisk4 number
      위험도가 '위험'에 해당하는 이슈 수
    • issueCountRisk5 number
      위험도가 '매우 위험'에 해당하는 이슈 수
    • resultSchemaVersion string
      분석 결과 형식 버전

예시 코드

import { AnalysisStatus } from 'sparrow-ondemand-node-sdk';

let analysisStatusResponse = null;

while (true) {
analysisStatusResponse = await client.getAnalysisStatus(
analysisRequestResponse.requestId,
);
if (analysisStatusResponse.result === null) {
console.log('분석이 진행 중');
// 20초 대기
await new Promise((resolve) => setTimeout(resolve, 20000));
} else {
console.log('분석 종료', analysisStatusResponse);
break;
}
}

3. 분석 결과 다운로드

분석이 완료됐다면 분석 결과 파일을 다운로드 받을 수 있습니다.

await client.downloadAnalysisResult({
requestId,
index,
filePath,
});

downloadAnalysisResult 메소드를 호출하면 지정한 file path에 분석 결과 파일이 다운로드됩니다.

파라미터

  • requestId 필수 number
    분석 요청 id입니다.
  • index 필수 number
    분석 시 분석 리스트 index
  • filePath 필수 string
    분석 다운로드 file path 입니다. path에는 파일 이름까지 명시돼야하며 zip 확장자만 지원합니다.
    ex) /home/result.zip

반환값

Promise<void>


4. 분석 중지

진행 중인 분석을 중지할 수 있습니다.

await client.stopAnalysis(requestId);

파라미터

  • requestId 필수 number
    분석 요청 id입니다.

반환값

Promise<void>



OndemandException

OndemandException은 RuntimeException을 통해 예외를 전달하며 두가지로 분류됩니다.

  • OndmandClientException
    온디맨드 서비스에 요청을 보내거나 응답 처리 로직을 수행할 때 클라이언트단에 발생합니다.
    • resultCode string
      exception 발생 원인 코드 정보를 담고 있습니다.
    • message string
      예외 메시지를 담고있습니다.
  • OndmandServerException
    온디맨드 서비스가 성공적으로 요청을 받았지만 처리하지 못해 에러 응답을 반환하는 경우 발생합니다.
    • resultCode string
      exception 발생 원인 코드 정보를 담고 있습니다.
    • message string
      예외 메세지를 담고있습니다.
    • statusCode number
      응답 상태 코드를 나타냅니다.
    • errors any[ ]
      요청 유효성 검증 실패 시 서버에서 반환되는 상세 실패 메시지입니다.

ANALYSIS_STATUS

분석 상태를 나타내며 7가지로 구분됩니다.

  • INIT
    분석을 진행 하기 위한 초기화 진행 중임을 나타냅니다.
  • READY
    초기화 완료 후 분석 준비 진행 중임을 나타냅니다.
  • PRE_PROCESS
    분석을 위한 전처리 진행 중임을 나타냅니다.
  • ANALYSIS
    분석 진행 중임을 나타냅니다.
  • POST_PROCESS
    분석이 완료 된 후 결과 처리 진행 중임을 나타냅니다.
  • COMPLETE
    분석 , 결과 처리 모두 완료된 상태를 나타냅니다.
  • STOP
    분석이 중지된 상태를 나타냅니다.

ANALYSIS_RESULT

분석 결과값을 나타냅니다.

  • SUCCESS
    분석이 성공했음을 의미합니다.
  • FAIL
    분석이 실패했음을 의미합니다.
  • STOPPED 분석이 중지됐음을 의미합니다.