feat(performance): GS샵 연결 테스트·원본 데이터 확인 — 제휴 API AES256 토큰

- 인증: 헤더 supCd + token = base64(AES256(yyyyMMddHHmmss + 협력사코드)), 암호화 모드는 문서에 없어
  CBC(IV=키 앞 16) → ECB → CBC(IV=0) 순서로 시도하고 통과한 모드 기억, HTTP 200 + result=fail 401 도 인증 실패로
- 운영 주소 withgs-api.gsshop.com, 매출 내역(매출인식일, 10일씩·쪽 넘김)·배송비 내역
- 설정 "쇼핑몰 원본 데이터 확인"에 GS샵 — 응답 항목 이름이 문서에 없어 실데이터로 매출 규칙 확정 예정
  (그 전까지 매출 수집은 연동 준비 중)
- 입력칸 라벨: 협력사코드(supCd)·AES256 암복호화 키(저장된 값 그대로 사용)
- 테스트 1개 추가(28개 통과), 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 14:27:49 +09:00
parent 3203ff87a4
commit e56c5685ca
6 changed files with 285 additions and 11 deletions
@@ -1198,6 +1198,91 @@ def test_sync_job_progress():
assert jobs.get_job(job.id) is job and jobs.running_job() is None
def test_gsshop_token_connection_and_probe():
"""GS샵: token = AES256(yyyyMMddHHmmss + 협력사코드), 헤더 supCd·token. 암호화 모드를 모르니 순서대로 시도해
통과한 모드를 기억. 인증 오류는 HTTP 200 + result=fail/code 401. 원본 확인은 10일씩·쪽 넘김, 키는 문구에 없음."""
import base64
from datetime import datetime
import httpx
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from app.modules.performance.adapters import gsshop as gs
from app.modules.performance.adapters.base import AdapterContext
key = "0123456789abcdef0123456789ABCDEF" # 32바이트 = AES256
def decrypt(tok, mode):
m = {"ecb": modes.ECB(), "cbc-zeroiv": modes.CBC(b"\0" * 16)}.get(mode, modes.CBC(key.encode()[:16]))
d = Cipher(algorithms.AES(key.encode()), m).decryptor()
raw = d.update(base64.b64decode(tok)) + d.finalize()
u = padding.PKCS7(128).unpadder()
return (u.update(raw) + u.finalize()).decode()
now = datetime(2018, 10, 17, 17, 49, 13)
for mode in gs.TOKEN_MODES:
assert decrypt(gs.make_token(key, "1036018", now, mode), mode) == "201810171749131036018"
try:
gs.make_token("short-key", "1", now, "ecb")
except AuthFailed as exc:
assert "short-key" not in exc.message
else:
raise AssertionError("키 길이 오류여야 합니다")
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
ctx = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key=key))
calls = []
def get(url, params=None, headers=None, timeout=None):
assert headers["supCd"] == "1036018" and params["supCode"] == "1036018"
# 서버는 ECB 로 풀어 본다고 가정 — CBC 토큰은 거부(HTTP 200 + result=fail)
try:
plain = decrypt(headers["token"], "ecb")
except Exception: # noqa: BLE001
plain = ""
if not plain.endswith("1036018"):
return httpx.Response(200, json={"result": "fail", "message": "키 인증 중 오류가 발생하였습니다.", "code": "401 UNAUTHORIZED"})
calls.append((url, dict(params)))
if url.endswith("/sales"):
return httpx.Response(200, json={"data": [], "hasMorePage": False, "totalCount": 3})
page = params["pageIdx"]
more = url.endswith("/sales/period") and params["fromDate"] == "20260901" and page == 1
rows = [{"ordNo": f"{params['fromDate']}-{page}", "saleAmt": 10000, "custNm": "홍길동", "prdNm": "밀폐용기"}]
return httpx.Response(200, json={"data": rows, "hasMorePage": more, "totalCount": 2 if more else 1})
orig = httpx.get
httpx.get = get
try:
msg = gs.GsshopAdapter().test_connection(ctx)
assert "연결 정상" in msg and "3건" in msg and "ECB" in msg
adapter = gs.GsshopAdapter()
rec = adapter.reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 15)) # 10일 + 5일
sales, ship = rec["probes"]
assert sales["ok"] and sales["count"] == 3 and ship["ok"] and ship["count"] == 2 # 9/1 두 쪽 + 9/11
f = {x["name"]: x for x in sales["fields"]}
assert f["saleAmt"]["sum"] == 30000 and f["custNm"]["personal"] and f["custNm"]["sample"] == ""
assert f["prdNm"]["sample"] == "밀폐용기" and "홍길동" not in repr(rec)
periods = {(p["fromDate"], p["toDate"]) for u, p in calls if u.endswith("/sales/period")}
assert periods == {("20260901", "20260910"), ("20260911", "20260915")}
# 틀린 키 → 세 가지 모드 모두 거부 → 인증 실패(키는 문구에 없음)
bad = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="X" * 32))
try:
gs.GsshopAdapter().test_connection(bad)
except AuthFailed as exc:
assert "X" * 32 not in exc.message and "3가지" in exc.message
else:
raise AssertionError("인증 실패여야 합니다")
finally:
httpx.get = orig
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0