Compare commits
27 Commits
main
...
hmm-backof
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ce0341102 | ||
|
|
2d0b5a3c1e | ||
|
|
cbd49b6b05 | ||
|
|
84029ed633 | ||
|
|
6394bbf078 | ||
|
|
2f5fc2bfbd | ||
|
|
66fcb5d149 | ||
|
|
b13b913939 | ||
|
|
c0c5a36ba0 | ||
|
|
cc2c3e3e25 | ||
|
|
c519435266 | ||
|
|
ad1e4573a9 | ||
|
|
2bd373bcb3 | ||
|
|
7d53b5c75c | ||
|
|
fbf4c19c72 | ||
|
|
1c8ad8647f | ||
|
|
90c771af57 | ||
|
|
de0956ef03 | ||
|
|
2c790f76b7 | ||
|
|
91c96d7919 | ||
|
|
89a6f4e4bc | ||
|
|
e6432fa943 | ||
|
|
cbc645466b | ||
|
|
35782b8a50 | ||
|
|
7dd47d39b9 | ||
|
|
d868d7bbb8 | ||
|
|
9f46205057 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,6 @@
|
||||
# 환경/비밀 — 절대 commit 금지
|
||||
.env
|
||||
.runtime/
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
|
||||
28
AGENTS.md
Normal file
28
AGENTS.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# 문서 작성 공통 규칙
|
||||
|
||||
이 저장소에서 새 문서를 만들거나 기존 문서를 크게 고칠 때는 아래 구조를 기본으로 한다.
|
||||
|
||||
1. 첫 문서(`README.md`)는 독자가 2~3분 안에 목적, 범위, 결정사항, 전체 구성, 현재 상태를 파악하는 **개요 문서**로 작성한다.
|
||||
2. README에는 복잡한 절차와 모든 오류 사례를 누적하지 않는다. 아래와 같이 역할별 상세 문서로 분리하고, 개요에서 명확한 링크를 제공한다.
|
||||
- `architecture.md`: 신뢰 경계, 컴포넌트 책임, 데이터·인증 흐름, 설계 결정
|
||||
- `cookbook.md`: 준비물, 단계별 적용 명령/화면값, 검증, 롤백
|
||||
- `troubleshooting.md`: 증상 → 원인 → 확인 방법 → 해결 → 재발 방지
|
||||
- 필요하면 `operations.md`, `security.md`, `adr/` 등 목적이 드러나는 파일을 추가한다.
|
||||
3. 그림은 한 장에 모든 세부사항을 넣지 않는다.
|
||||
- README에는 시스템 경계와 핵심 흐름만 보이는 **개요도**를 둔다.
|
||||
- 상세 연결·claim·포트·예외 흐름은 architecture 또는 cookbook의 **상세도**로 분리한다.
|
||||
- 각 그림 아래에는 독자가 알아야 할 결론을 한두 문장으로 적는다.
|
||||
4. Cookbook은 실제 적용 순서를 따르며, 각 단계에 입력값의 출처, 성공 판정, 실패 시 연결할 troubleshooting 항목을 포함한다.
|
||||
5. 비밀번호, client secret, access token, 개인 식별 정보는 어떤 문서·그림·명령 출력에도 기록하지 않는다. 위치와 안전한 조회/rotation 방법만 기록한다.
|
||||
6. README의 문서 지도와 각 상세 문서의 상호 링크를 변경 후 반드시 확인한다.
|
||||
|
||||
문서의 독자는 운영자·개발자·검토자다. 제품명과 전문 용어는 필요할 때만 쓰고, 처음 한 번은 평이한 말로 역할을 정의한다.
|
||||
|
||||
## HMM Select AI·HTML 리포트 보호 기준
|
||||
|
||||
1. 사용자 권한이 적용되는 HMM MCP의 기준 endpoint는 `https://hmm-backoffice.cloud-handson.com/mcp`다.
|
||||
2. MCP route `search_carrier_performance`는 기존 DB Agent Tool `HMM_CARRIER_FEDERATION_SEARCH`를 호출한다. 이 Tool은 자연어를 Select AI Federation으로 처리하며, 고정 SQL·고정 데이터·대체 package로 바꾸지 않는다.
|
||||
3. `hmm-mcp.cloud-handson.com`은 별도 호환성·무 VPD 시험 환경이다. 기준 endpoint나 운영 Select AI 경로의 대체재로 사용하지 않는다.
|
||||
4. HTML 기능 추가 범위는 후속 표현 Tool `HMM_CARRIER_REPORT_RENDERER`와 포털의 범용 이전 결과 전달뿐이다. 렌더러는 사용자·권한·업무 데이터를 다시 조회하거나 보충하지 않는다.
|
||||
5. 조회 Tool, target, package 또는 endpoint를 생성·삭제·교체하기 전에는 현재 MCP discovery, `BACKOFFICE_MCP_TOOLS`, DB Agent Tool metadata를 먼저 대조한다. 기존 조회 경로 변경은 사용자가 명시적으로 요청한 경우에만 한다.
|
||||
6. 회귀 검증은 같은 Bearer 문맥에서 `search_carrier_performance`의 원본 행 수와 renderer에 전달된 `rows` 수가 같은지 확인한다. 대표 시나리오의 현재 기준은 E1001 팀장 질문에 대한 8건이지만, 코드는 E1001이나 8을 조건으로 사용하지 않는다.
|
||||
@@ -3,6 +3,11 @@
|
||||
|
||||
# MCP
|
||||
HMM_MCP_BEARER_TOKEN=
|
||||
HMM_MCP_BEARER_TOKEN_E1001=
|
||||
HMM_MCP_BEARER_TOKEN_E1002=
|
||||
HMM_MCP_BEARER_TOKEN_E1003=
|
||||
HMM_MCP_BEARER_TOKEN_E1005=
|
||||
HMM_MCP_BEARER_TOKEN_E1007=
|
||||
AI_WEB_AGENT_CONSOLE_MCP_TIMEOUT_SECONDS=45
|
||||
|
||||
# OCI Generative AI SDK
|
||||
|
||||
@@ -41,7 +41,9 @@ python3 -m venv .venv
|
||||
- `config/hmm_hr_query_contracts.json`: 질의별 필수 근거와 계산·시간 규칙
|
||||
|
||||
실제 토큰, DB 비밀번호, Wallet, OCI private key는 Git에 넣지 않는다. 데모 사용자 JSON은
|
||||
`HMM_MCP_BEARER_TOKEN` 같은 환경변수 이름만 참조한다.
|
||||
`HMM_MCP_BEARER_TOKEN_E1001`처럼 사용자별 환경변수 이름만 참조한다. token 원문은 설정 JSON이나
|
||||
문서에 기록하지 않는다. 사용자 preset들이 같은 환경변수를 공유하면 화면의 사용자만 바뀌고 DB
|
||||
권한 문맥은 바뀌지 않으므로 허용하지 않는다.
|
||||
|
||||
## 검증
|
||||
|
||||
|
||||
@@ -443,17 +443,28 @@ def _is_failed_synthesis_answer(value: object) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def load_chat_context(conversation_id: str) -> list[dict[str, str]]:
|
||||
def load_chat_context(
|
||||
conversation_id: str,
|
||||
*,
|
||||
selected_user_id: str = "",
|
||||
) -> list[dict[str, str]]:
|
||||
current_user_id = str(selected_user_id or "").strip()
|
||||
with _chat_db_connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT question, answer
|
||||
FROM poc4_mcp_chat_turns
|
||||
WHERE conversation_id = ?
|
||||
AND (? = '' OR selected_user_id = ?)
|
||||
ORDER BY turn_id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(conversation_id, CHAT_CONTEXT_TURNS),
|
||||
(
|
||||
conversation_id,
|
||||
current_user_id,
|
||||
current_user_id,
|
||||
CHAT_CONTEXT_TURNS,
|
||||
),
|
||||
).fetchall()
|
||||
messages: list[dict[str, str]] = []
|
||||
for row in reversed(rows):
|
||||
@@ -2633,6 +2644,14 @@ def _mcp_response_payload(mcp_result: Any) -> Mapping[str, Any]:
|
||||
if isinstance(mcp_result, Mapping):
|
||||
response = mcp_result.get("response")
|
||||
if isinstance(response, Mapping):
|
||||
nested_result = response.get("result")
|
||||
if isinstance(nested_result, str):
|
||||
try:
|
||||
parsed = json.loads(nested_result)
|
||||
except ValueError:
|
||||
parsed = None
|
||||
if isinstance(parsed, Mapping):
|
||||
return parsed
|
||||
return response
|
||||
return mcp_result
|
||||
return {}
|
||||
@@ -2643,12 +2662,47 @@ def _mcp_generated_sql(mcp_result: Any) -> str:
|
||||
return str(payload.get("generatedSql") or payload.get("generated_sql") or "").strip()
|
||||
|
||||
|
||||
def _mcp_rendered_html(mcp_result: Any) -> str:
|
||||
"""Extract an HTML artifact without coupling the UI to a tool name."""
|
||||
|
||||
payload = _mcp_response_payload(mcp_result)
|
||||
candidate = payload.get("html") or payload.get("rendered_html")
|
||||
if not isinstance(candidate, str):
|
||||
return ""
|
||||
html_text = candidate.strip()
|
||||
if len(html_text) > 1_000_000 or "<" not in html_text or ">" not in html_text:
|
||||
return ""
|
||||
return html_text
|
||||
|
||||
|
||||
def _mcp_items(mcp_result: Any) -> list[Any]:
|
||||
payload = _mcp_response_payload(mcp_result)
|
||||
items = payload.get("items")
|
||||
return items if isinstance(items, list) else []
|
||||
|
||||
|
||||
def _mcp_structured_rows(value: Any) -> list[Any]:
|
||||
"""Extract row arrays from common MCP wrappers, including JSON strings."""
|
||||
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return _mcp_structured_rows(json.loads(value))
|
||||
except ValueError:
|
||||
return []
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
if not isinstance(value, Mapping):
|
||||
return []
|
||||
|
||||
for key in ("items", "results", "rows", "response", "result"):
|
||||
if key not in value:
|
||||
continue
|
||||
rows = _mcp_structured_rows(value.get(key))
|
||||
if rows:
|
||||
return rows
|
||||
return []
|
||||
|
||||
|
||||
def _mcp_summary(mcp_result: Any) -> dict[str, Any]:
|
||||
if not isinstance(mcp_result, Mapping):
|
||||
return {"type": type(mcp_result).__name__}
|
||||
@@ -2692,11 +2746,91 @@ def _agent_tool_catalog(
|
||||
if isinstance(properties, Mapping)
|
||||
else [],
|
||||
"read_only": route.tool.read_only,
|
||||
"consumes_previous_result": _is_presentation_route(route),
|
||||
}
|
||||
)
|
||||
return catalog, routes
|
||||
|
||||
|
||||
def _is_presentation_route(route: RoutedMcpTool) -> bool:
|
||||
"""Identify a renderer from its discovered description and input schema."""
|
||||
|
||||
properties = route.tool.schema.get("properties")
|
||||
names = (
|
||||
[str(name).casefold() for name in properties]
|
||||
if isinstance(properties, Mapping)
|
||||
else []
|
||||
)
|
||||
has_payload_input = any(
|
||||
any(marker in name for marker in ("report", "payload", "render_data"))
|
||||
and any(marker in name for marker in ("json", "data", "payload"))
|
||||
for name in names
|
||||
)
|
||||
description = f"{route.tool.name} {route.tool.description}".casefold()
|
||||
has_presentation_intent = any(
|
||||
marker in description
|
||||
for marker in ("render", "html", "dashboard", "presentation", "report")
|
||||
)
|
||||
has_prior_result_contract = any(
|
||||
marker in description
|
||||
for marker in (
|
||||
"supplied",
|
||||
"already-authorized",
|
||||
"previous result",
|
||||
"input data",
|
||||
"후속 처리",
|
||||
"조회 결과",
|
||||
"선행 결과",
|
||||
)
|
||||
)
|
||||
return has_payload_input and has_presentation_intent and has_prior_result_contract
|
||||
|
||||
|
||||
def _question_requests_presentation(question: str) -> bool:
|
||||
text = str(question or "").casefold()
|
||||
return any(
|
||||
marker in text
|
||||
for marker in (
|
||||
"리포트",
|
||||
"보고서",
|
||||
"대시보드",
|
||||
"차트",
|
||||
"그래프",
|
||||
"html",
|
||||
"화면으로 만들어",
|
||||
"문서로 만들어",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _presentation_route(
|
||||
routes_by_key: Mapping[str, RoutedMcpTool],
|
||||
attempted_route_keys: set[str],
|
||||
) -> tuple[str, RoutedMcpTool] | None:
|
||||
return next(
|
||||
(
|
||||
(key, route)
|
||||
for key, route in routes_by_key.items()
|
||||
if key not in attempted_route_keys and _is_presentation_route(route)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _primary_data_route(
|
||||
routes_by_key: Mapping[str, RoutedMcpTool],
|
||||
attempted_route_keys: set[str],
|
||||
) -> tuple[str, RoutedMcpTool] | None:
|
||||
return next(
|
||||
(
|
||||
(key, route)
|
||||
for key, route in routes_by_key.items()
|
||||
if key not in attempted_route_keys and not _is_presentation_route(route)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _complex_reasoning_model_profile(default_model_profile: str) -> str:
|
||||
configured = (
|
||||
os.environ.get(COMPLEX_REASONING_MODEL_PROFILE_ENV)
|
||||
@@ -2740,6 +2874,339 @@ def _clean_agent_tool_query(value: object, fallback: str) -> str:
|
||||
return " ".join(cleaned).strip() or fallback
|
||||
|
||||
|
||||
def _camel_case_key(value: object) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not re.search(r"[\s_-]", text):
|
||||
return text[:1].lower() + text[1:]
|
||||
parts = [part for part in re.split(r"[\s_-]+", text.casefold()) if part]
|
||||
return (
|
||||
parts[0] + "".join(part[:1].upper() + part[1:] for part in parts[1:])
|
||||
if parts
|
||||
else text
|
||||
)
|
||||
|
||||
|
||||
def _normalize_presentation_value(value: Any) -> Any:
|
||||
if isinstance(value, Mapping):
|
||||
return {
|
||||
_camel_case_key(key): _normalize_presentation_value(item)
|
||||
for key, item in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_normalize_presentation_value(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def _clean_presentation_title(value: Any) -> str:
|
||||
text = html.unescape(re.sub(r"<[^>]+>", " ", str(value or "")))
|
||||
text = " ".join(text.split()).strip(" \t\r\n\"'`-–—:;,.!?·")
|
||||
if len(text) > 48:
|
||||
text = text[:47].rstrip() + "…"
|
||||
return text or "업무 현황"
|
||||
|
||||
|
||||
def _fallback_presentation_data_query(question: str) -> str:
|
||||
text = " ".join(str(question or "").split()).strip()
|
||||
text = re.sub(
|
||||
r"\s*(?:그리고\s*)?(?:(?:이걸|이를|그\s*결과를|결과를)\s*)?"
|
||||
r"(?:HMM\s*)?(?:HTML|리포트|보고서|대시보드|차트)\s*"
|
||||
r"(?:형식)?(?:으로|로)?\s*(?:만들어|생성해|작성해|보여)\s*"
|
||||
r"(?:줘|주세요)?\s*[.!?]?\s*$",
|
||||
" 보여줘",
|
||||
text,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
text = re.sub(
|
||||
r"(?i)HTML\s*(?:형식)?(?:으로|로)?\s*",
|
||||
"",
|
||||
text,
|
||||
)
|
||||
text = re.sub(
|
||||
r"(?:HMM\s*)?(?:리포트|보고서|대시보드|차트)\s*"
|
||||
r"(?:형식)?(?:으로|로)?\s*(?:만들어|생성해|작성해|보여)\s*"
|
||||
r"(?:줘|주세요)?",
|
||||
"보여줘",
|
||||
text,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
return " ".join(text.split()).strip() or str(question or "").strip()
|
||||
|
||||
|
||||
def _plan_presentation_data_query(
|
||||
*,
|
||||
question: str,
|
||||
route: RoutedMcpTool,
|
||||
model_profile_key: str,
|
||||
) -> str:
|
||||
"""Separate the data request from its presentation-format request."""
|
||||
|
||||
fallback = _fallback_presentation_data_query(question)
|
||||
try:
|
||||
profile = resolve_model_profile(model_profile_key)
|
||||
client = build_oci_genai_completion_client(
|
||||
profile.model_id,
|
||||
profile.answer_model_region,
|
||||
profile.answer_model_endpoint,
|
||||
)
|
||||
text = client.complete(
|
||||
system_prompt=(
|
||||
"Rewrite the Korean request as a data-retrieval question for the selected "
|
||||
"MCP tool. Preserve every business subject, identifier, filter, period, and "
|
||||
"requested metric. Remove only presentation-format and artifact-generation "
|
||||
"instructions such as HTML, report, dashboard, chart, render, 보여주는 형식, "
|
||||
"or 만들어줘. Do not answer the question, write SQL, or request a token. "
|
||||
"The rewritten query must ask for ordinary structured data rows, never HTML "
|
||||
"tags, Markdown, or preformatted table rows. Return only schema JSON."
|
||||
),
|
||||
user_prompt=json.dumps(
|
||||
{
|
||||
"question": question,
|
||||
"selected_tool": route.tool.name,
|
||||
"tool_description": route.tool.description[:1200],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"additionalProperties": False,
|
||||
"required": ["data_query"],
|
||||
"properties": {"data_query": {"type": "string"}},
|
||||
},
|
||||
max_tokens=300,
|
||||
temperature=temperature_for_model_profile(profile),
|
||||
)
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, Mapping):
|
||||
planned = _clean_agent_tool_query(parsed.get("data_query"), fallback)
|
||||
return _fallback_presentation_data_query(planned or fallback)
|
||||
except Exception:
|
||||
pass
|
||||
return fallback
|
||||
|
||||
|
||||
def _mcp_rows_contain_presentation_markup(value: Any) -> bool:
|
||||
rows = _mcp_structured_rows(value)
|
||||
if not rows:
|
||||
return False
|
||||
for row in rows:
|
||||
if not isinstance(row, Mapping):
|
||||
continue
|
||||
keys = {str(key).casefold() for key in row}
|
||||
if keys & {"htmlrow", "html", "markdown"}:
|
||||
return True
|
||||
if any(
|
||||
isinstance(item, str)
|
||||
and re.search(r"<(?:tr|td|table|div)\b", item, flags=re.IGNORECASE)
|
||||
for item in row.values()
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _plan_presentation_title(
|
||||
*,
|
||||
question: str,
|
||||
source_step: Mapping[str, Any],
|
||||
model_profile_key: str,
|
||||
selected_user_id: str = "",
|
||||
) -> str:
|
||||
"""Generate a concise business title without coupling to a specific report."""
|
||||
|
||||
fallback = "업무 현황"
|
||||
try:
|
||||
profile = resolve_model_profile(model_profile_key)
|
||||
client = build_oci_genai_completion_client(
|
||||
profile.model_id,
|
||||
profile.answer_model_region,
|
||||
profile.answer_model_endpoint,
|
||||
)
|
||||
text = client.complete(
|
||||
system_prompt=(
|
||||
"Create one concise Korean enterprise report heading. Preserve the "
|
||||
"business subject, team/user scope, and identifiers. Remove output-format "
|
||||
"and action phrases such as HTML, report, dashboard, 보여줘, 만들어줘. "
|
||||
"The current selected user ID is authoritative. First-person expressions "
|
||||
"such as 내, 나, and 우리 refer to that current user, never to a user from "
|
||||
"earlier conversation turns. Do not change the current user into a manager "
|
||||
"or another employee unless the latest question explicitly names that scope. "
|
||||
"Use a noun phrase, not a sentence. The template separately appends a fixed "
|
||||
"subtitle, so do not include '최신 선사 실적'. Return only schema JSON."
|
||||
),
|
||||
user_prompt=json.dumps(
|
||||
{
|
||||
"question": question,
|
||||
"current_selected_user_id": str(selected_user_id or "").strip(),
|
||||
"source_tool": str(source_step.get("tool_name") or ""),
|
||||
"source_rows": len(
|
||||
_mcp_structured_rows(source_step.get("mcp_result", {}))
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
response_schema={
|
||||
"type": "object",
|
||||
"additionalProperties": False,
|
||||
"required": ["title"],
|
||||
"properties": {"title": {"type": "string"}},
|
||||
},
|
||||
max_tokens=120,
|
||||
temperature=temperature_for_model_profile(profile),
|
||||
)
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, Mapping):
|
||||
return _clean_presentation_title(parsed.get("title"))
|
||||
except Exception:
|
||||
pass
|
||||
return fallback
|
||||
|
||||
|
||||
def _presentation_payload(
|
||||
question: str,
|
||||
steps: list[Mapping[str, Any]],
|
||||
*,
|
||||
title: str = "",
|
||||
selected_user_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Build a renderer payload only from the preceding authorized tool result."""
|
||||
|
||||
source = next(
|
||||
(
|
||||
step
|
||||
for step in reversed(steps)
|
||||
if not bool(step.get("consumes_previous_result"))
|
||||
),
|
||||
{},
|
||||
)
|
||||
raw_result = source.get("mcp_result", {}) if isinstance(source, Mapping) else {}
|
||||
source_rows = _mcp_structured_rows(raw_result)
|
||||
rows = [
|
||||
_normalize_presentation_value(row)
|
||||
for row in source_rows
|
||||
if isinstance(row, Mapping)
|
||||
]
|
||||
requester = re.search(r"\bE\d{4,}\b", str(question or ""), flags=re.IGNORECASE)
|
||||
requested_by = str(selected_user_id or "").strip().upper()
|
||||
if not requested_by and requester:
|
||||
requested_by = requester.group(0).upper()
|
||||
source_tool = str(source.get("tool_name") or "MCP data query")
|
||||
return {
|
||||
"report": {
|
||||
"id": "MCP-REPORT",
|
||||
"category": "MCP Business Intelligence",
|
||||
"title": _clean_presentation_title(title),
|
||||
"question": str(question or ""),
|
||||
"requestedBy": requested_by or "-",
|
||||
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"answer": (
|
||||
f"{source_tool}에서 권한 범위 내 결과 {len(rows)}건을 받아 "
|
||||
"리포트로 구성했습니다."
|
||||
),
|
||||
"execution": {
|
||||
"server": str(source.get("server_id") or ""),
|
||||
"tool": source_tool,
|
||||
"calls": len(steps) + 1,
|
||||
},
|
||||
"evidence": [f"MCP {source_tool} 결과 {len(rows)}건 반환"],
|
||||
"limitation": "표시 값은 선행 MCP 데이터 조회 결과만 사용했습니다.",
|
||||
},
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def _build_mcp_arguments(
|
||||
*,
|
||||
route: RoutedMcpTool,
|
||||
tool_query: str,
|
||||
limit: int,
|
||||
preferred_tool: str,
|
||||
steps: list[Mapping[str, Any]],
|
||||
presentation_title: str = "",
|
||||
selected_user_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
if not _is_presentation_route(route):
|
||||
return build_mcp_tool_arguments(
|
||||
route.tool,
|
||||
tool_query,
|
||||
int(limit),
|
||||
preferred_tool=preferred_tool,
|
||||
)
|
||||
properties = route.tool.schema.get("properties")
|
||||
if not isinstance(properties, Mapping):
|
||||
raise McpToolRouterError("렌더링 MCP tool의 입력 스키마가 없습니다.")
|
||||
input_name = next(
|
||||
(
|
||||
str(name)
|
||||
for name in properties
|
||||
if "report" in str(name).casefold()
|
||||
and any(
|
||||
marker in str(name).casefold()
|
||||
for marker in ("json", "payload", "data")
|
||||
)
|
||||
),
|
||||
"",
|
||||
)
|
||||
if not input_name:
|
||||
raise McpToolRouterError("렌더링 MCP tool이 report payload 입력을 선언하지 않았습니다.")
|
||||
return {
|
||||
input_name: json.dumps(
|
||||
_presentation_payload(
|
||||
tool_query,
|
||||
steps,
|
||||
title=presentation_title,
|
||||
selected_user_id=selected_user_id,
|
||||
),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _presentation_artifact_summary(
|
||||
mcp_result: Any,
|
||||
agent_steps: list[Mapping[str, Any]] | None,
|
||||
) -> dict[str, Any]:
|
||||
if not _mcp_rendered_html(mcp_result):
|
||||
return {}
|
||||
title = "업무 현황"
|
||||
row_count = 0
|
||||
for step in reversed(agent_steps or []):
|
||||
if not isinstance(step, Mapping):
|
||||
continue
|
||||
if not bool(step.get("consumes_previous_result")):
|
||||
row_count = len(_mcp_structured_rows(step.get("mcp_result", {})))
|
||||
continue
|
||||
arguments = step.get("arguments")
|
||||
if not isinstance(arguments, Mapping):
|
||||
continue
|
||||
for raw_payload in arguments.values():
|
||||
if not isinstance(raw_payload, str):
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(raw_payload)
|
||||
except ValueError:
|
||||
continue
|
||||
report = parsed.get("report") if isinstance(parsed, Mapping) else None
|
||||
if isinstance(report, Mapping):
|
||||
title = _clean_presentation_title(report.get("title"))
|
||||
rows = parsed.get("rows")
|
||||
if isinstance(rows, list):
|
||||
row_count = len(rows)
|
||||
break
|
||||
return {"title": title, "row_count": row_count}
|
||||
|
||||
|
||||
def _presentation_completion_answer(
|
||||
mcp_result: Any,
|
||||
agent_steps: list[Mapping[str, Any]] | None,
|
||||
) -> str:
|
||||
artifact = _presentation_artifact_summary(mcp_result, agent_steps)
|
||||
if not artifact:
|
||||
return ""
|
||||
return (
|
||||
f"**{artifact['title']}** 리포트를 생성했습니다. "
|
||||
f"아래 생성된 리포트에서 조회 결과 {artifact['row_count']}건을 확인할 수 있습니다."
|
||||
)
|
||||
|
||||
|
||||
def _mcp_has_actionable_result(mcp_result: Any) -> bool:
|
||||
if _mcp_generated_sql(mcp_result) or _mcp_items(mcp_result):
|
||||
return True
|
||||
@@ -3231,6 +3698,29 @@ def plan_mcp_execution_mode(
|
||||
"reason": f"사용자 선택: {override}",
|
||||
"model_profile": "",
|
||||
}
|
||||
presentation_routes = [route for route in routed_tools if _is_presentation_route(route)]
|
||||
if _question_requests_presentation(question) and presentation_routes:
|
||||
data_routes = [route for route in routed_tools if not _is_presentation_route(route)]
|
||||
primary = data_routes[0] if data_routes else fallback
|
||||
if len(data_routes) > 1:
|
||||
try:
|
||||
primary = route_mcp_tool_across_servers_with_llm(
|
||||
data_routes,
|
||||
question,
|
||||
router_model_profile=model_profile_key,
|
||||
)
|
||||
except McpToolRouterError:
|
||||
pass
|
||||
if primary is not fallback or len(routed_tools) > 1:
|
||||
return {
|
||||
"mode": "agent",
|
||||
"route_key": _route_key(primary.server_id, primary.tool.name),
|
||||
"reason": (
|
||||
"리포트·차트·HTML 요청이며, 발견된 렌더링 도구가 이전 구조화 "
|
||||
"결과를 입력으로 선언했습니다. 데이터 조회 후 렌더링을 순차 실행합니다."
|
||||
),
|
||||
"model_profile": model_profile_key,
|
||||
}
|
||||
if len(routed_tools) <= 1:
|
||||
return {
|
||||
"mode": "single",
|
||||
@@ -3276,7 +3766,10 @@ def plan_mcp_execution_mode(
|
||||
"the user's Korean question should be answered with one MCP "
|
||||
"tool call or with a multi-tool ReAct loop. Prefer mode=single "
|
||||
"unless the question explicitly requires comparing, combining, "
|
||||
"or validating evidence across different MCP tools/sources. "
|
||||
"or validating evidence across different MCP tools/sources. A route "
|
||||
"whose consumes_previous_result flag is true is a presentation renderer: "
|
||||
"when the user asks for a report, dashboard, chart, document, or HTML, "
|
||||
"choose mode=agent so a data route runs first and that renderer runs next. "
|
||||
"Return only JSON matching the schema. Never request or expose "
|
||||
"bearer tokens."
|
||||
),
|
||||
@@ -3290,7 +3783,8 @@ def plan_mcp_execution_mode(
|
||||
),
|
||||
"agent_policy": (
|
||||
"use agent only for cross-source comparison, contract "
|
||||
"plus terms/document search, or multi-step validation"
|
||||
"plus terms/document search, multi-step validation, or a "
|
||||
"data-result-to-presentation rendering sequence"
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
@@ -3360,6 +3854,10 @@ def _plan_agent_step(
|
||||
"If no tool has been called yet, choose action=call_tool. "
|
||||
"After each observation, decide whether another tool call is needed "
|
||||
"or action=final_answer is enough. Do not expose or request bearer tokens. "
|
||||
"A route with consumes_previous_result=true is a renderer. For a report, "
|
||||
"dashboard, chart, document, or HTML request, call a data route first, "
|
||||
"then call that renderer using the previous structured result; do not "
|
||||
"finish with text only before the renderer has been attempted. "
|
||||
"tool_query must be plain natural-language query text only; do not include "
|
||||
"argument labels such as limit:, prompt:, query:, top_k:, or candidate_k:. "
|
||||
"Do not write SQL. Preserve identifiers exactly. If the user says "
|
||||
@@ -3417,6 +3915,8 @@ def run_mcp_agent_loop(
|
||||
bearer_token: str,
|
||||
limit: int,
|
||||
model_profile_key: str,
|
||||
selected_user_id: str = "",
|
||||
initial_route_key: str = "",
|
||||
progress_callback: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
tool_catalog, routes_by_key = _agent_tool_catalog(routed_tools)
|
||||
@@ -3431,8 +3931,21 @@ def run_mcp_agent_loop(
|
||||
|
||||
for step_no in range(1, MAX_AGENT_TOOL_STEPS + 1):
|
||||
forced_plan = None
|
||||
wants_presentation = _question_requests_presentation(question)
|
||||
if wants_presentation and _presentation_route(routes_by_key, attempted_route_keys):
|
||||
forced_plan = (
|
||||
(
|
||||
(initial_route_key, routes_by_key[initial_route_key])
|
||||
if not observations
|
||||
and initial_route_key in routes_by_key
|
||||
and not _is_presentation_route(routes_by_key[initial_route_key])
|
||||
else _primary_data_route(routes_by_key, attempted_route_keys)
|
||||
)
|
||||
if not observations
|
||||
else _presentation_route(routes_by_key, attempted_route_keys)
|
||||
)
|
||||
if step_no == 1 and _question_needs_cross_source(question):
|
||||
forced_plan = _select_unvisited_route(
|
||||
forced_plan = forced_plan or _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
@@ -3522,36 +4035,48 @@ def run_mcp_agent_loop(
|
||||
tool_query = _clean_agent_tool_query(plan.get("tool_query"), question)
|
||||
|
||||
if action == "final_answer" and observations:
|
||||
forced = _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
renderer = (
|
||||
_presentation_route(routes_by_key, attempted_route_keys)
|
||||
if wants_presentation
|
||||
else None
|
||||
)
|
||||
if forced is None or not _question_needs_cross_source(question):
|
||||
stop_reason = "planner가 추가 MCP 호출이 불필요하다고 판단했습니다."
|
||||
break
|
||||
route_key, route = forced
|
||||
action = "call_tool"
|
||||
tool_query = _fallback_tool_query_for_route(
|
||||
question,
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 비교·약관 질문인데 미호출 MCP route가 있어 "
|
||||
f"{route_key} 호출로 전환합니다."
|
||||
).strip(" /")
|
||||
if renderer is not None:
|
||||
route_key, route = renderer
|
||||
action = "call_tool"
|
||||
tool_query = question
|
||||
thought = "사용자 요청에 따른 이전 구조화 결과의 리포트 렌더링"
|
||||
else:
|
||||
forced = _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
)
|
||||
if forced is None or not _question_needs_cross_source(question):
|
||||
stop_reason = "planner가 추가 MCP 호출이 불필요하다고 판단했습니다."
|
||||
break
|
||||
route_key, route = forced
|
||||
action = "call_tool"
|
||||
tool_query = _fallback_tool_query_for_route(
|
||||
question,
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 비교·약관 질문인데 미호출 MCP route가 있어 "
|
||||
f"{route_key} 호출로 전환합니다."
|
||||
).strip(" /")
|
||||
if action != "call_tool" and not observations:
|
||||
action = "call_tool"
|
||||
route = routes_by_key.get(route_key)
|
||||
if route is None:
|
||||
route = next(iter(routes_by_key.values()))
|
||||
route_key = _route_key(route.server_id, route.tool.name)
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
if not _is_presentation_route(route):
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
is_distinct_vector_query = (
|
||||
_is_vector_route(route)
|
||||
and tool_query not in completed_vector_queries
|
||||
@@ -3576,11 +4101,12 @@ def run_mcp_agent_loop(
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
if not _is_presentation_route(route):
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 중복 MCP route {repeated_route_key} 대신 "
|
||||
f"미호출 route {route_key}로 전환합니다."
|
||||
@@ -3590,11 +4116,36 @@ def run_mcp_agent_loop(
|
||||
raise PublicMcpError("선택된 MCP 서버 설정을 찾지 못했습니다.")
|
||||
|
||||
started = perf_counter()
|
||||
arguments = build_mcp_tool_arguments(
|
||||
route.tool,
|
||||
tool_query,
|
||||
int(limit),
|
||||
presentation_title = ""
|
||||
if wants_presentation and not observations and not _is_presentation_route(route):
|
||||
tool_query = _plan_presentation_data_query(
|
||||
question=question,
|
||||
route=route,
|
||||
model_profile_key=model_profile_key,
|
||||
)
|
||||
if _is_presentation_route(route):
|
||||
source_step = next(
|
||||
(
|
||||
step
|
||||
for step in reversed(steps)
|
||||
if not bool(step.get("consumes_previous_result"))
|
||||
),
|
||||
{},
|
||||
)
|
||||
presentation_title = _plan_presentation_title(
|
||||
question=question,
|
||||
source_step=source_step,
|
||||
model_profile_key=model_profile_key,
|
||||
selected_user_id=selected_user_id,
|
||||
)
|
||||
arguments = _build_mcp_arguments(
|
||||
route=route,
|
||||
tool_query=question if _is_presentation_route(route) else tool_query,
|
||||
limit=int(limit),
|
||||
preferred_tool=server.default_tool,
|
||||
steps=steps,
|
||||
presentation_title=presentation_title,
|
||||
selected_user_id=selected_user_id,
|
||||
)
|
||||
raw_result = call_tool(
|
||||
base_url=server.endpoint_url,
|
||||
@@ -3604,6 +4155,14 @@ def run_mcp_agent_loop(
|
||||
)
|
||||
parsed = _content_text_json(raw_result)
|
||||
mcp_result = parsed if parsed is not None else raw_result
|
||||
if (
|
||||
wants_presentation
|
||||
and not _is_presentation_route(route)
|
||||
and _mcp_rows_contain_presentation_markup(mcp_result)
|
||||
):
|
||||
raise PublicMcpError(
|
||||
"데이터 조회 결과가 구조화 행이 아니라 표현용 마크업으로 반환됐습니다."
|
||||
)
|
||||
elapsed = perf_counter() - started
|
||||
summary = _mcp_summary(mcp_result)
|
||||
step = {
|
||||
@@ -3618,6 +4177,7 @@ def run_mcp_agent_loop(
|
||||
"mcp_result": mcp_result,
|
||||
"result_summary": summary,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"consumes_previous_result": _is_presentation_route(route),
|
||||
}
|
||||
steps.append(step)
|
||||
observations.append(
|
||||
@@ -3642,6 +4202,9 @@ def run_mcp_agent_loop(
|
||||
actionable_route_keys.add(route_key)
|
||||
if progress_callback:
|
||||
progress_callback(step)
|
||||
if _is_presentation_route(route):
|
||||
stop_reason = "이전 구조화 결과를 렌더링 MCP tool로 전달했습니다."
|
||||
break
|
||||
|
||||
if last is None:
|
||||
raise PublicMcpError("MCP agent가 실행한 tool 호출이 없습니다.")
|
||||
@@ -3666,6 +4229,11 @@ def _render_mcp_result_sections(
|
||||
execution_events = details.get("execution_events")
|
||||
generated_sql = _mcp_generated_sql(mcp_result)
|
||||
items = _mcp_items(mcp_result)
|
||||
rendered_html = _mcp_rendered_html(mcp_result)
|
||||
|
||||
if rendered_html:
|
||||
st.markdown("#### 생성된 리포트")
|
||||
components.html(rendered_html, height=1420, scrolling=True)
|
||||
|
||||
if isinstance(execution_events, list) and execution_events:
|
||||
with st.expander(f"처리 시간 로그 · {len(execution_events)}건"):
|
||||
@@ -3782,9 +4350,11 @@ def resolve_standalone_question(
|
||||
question: str,
|
||||
messages: list[Mapping[str, Any]],
|
||||
model_profile_key: str,
|
||||
selected_user_id: str = "",
|
||||
) -> str:
|
||||
context = _conversation_context(messages)
|
||||
if not context:
|
||||
current_user_id = str(selected_user_id or "").strip()
|
||||
if not context and not current_user_id:
|
||||
return question
|
||||
try:
|
||||
profile = resolve_model_profile(model_profile_key)
|
||||
@@ -3797,10 +4367,19 @@ def resolve_standalone_question(
|
||||
system_prompt=(
|
||||
"Rewrite the user's latest Korean question into one standalone "
|
||||
"MCP tool query. Use the conversation only to resolve references. "
|
||||
"The current selected user ID is authoritative. First-person expressions "
|
||||
"such as 내, 나, and 우리 refer only to the current selected user. Never "
|
||||
"reuse another user's identity, manager scope, or team scope from earlier "
|
||||
"conversation turns. If the latest question is self-contained, preserve its "
|
||||
"meaning and scope. "
|
||||
"Do not answer the question."
|
||||
),
|
||||
user_prompt=json.dumps(
|
||||
{"conversation": context, "latest_question": question},
|
||||
{
|
||||
"current_selected_user_id": current_user_id,
|
||||
"conversation": context,
|
||||
"latest_question": question,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
response_schema={
|
||||
@@ -4228,6 +4807,10 @@ def synthesize_answer(
|
||||
}
|
||||
for step in (agent_steps or [])
|
||||
],
|
||||
"presentation_artifact": _presentation_artifact_summary(
|
||||
mcp_result,
|
||||
agent_steps,
|
||||
),
|
||||
}
|
||||
return json.dumps(prompt_payload, ensure_ascii=False)
|
||||
|
||||
@@ -4311,7 +4894,11 @@ def synthesize_answer(
|
||||
"Show audit_log_id when it is provided. Follow every required_answer_checks item in the user "
|
||||
"payload. When the user requests a result list, include every "
|
||||
"row provided in the MCP evidence, up to 20 rows, and state the total "
|
||||
"returned row count. Do not arbitrarily stop at five rows. Keep the "
|
||||
"returned row count. Do not arbitrarily stop at five rows. If "
|
||||
"presentation_artifact is present, the HTML artifact is the final visual output: "
|
||||
"do not reproduce HTML tags, Markdown tables, or individual data rows in answer. "
|
||||
"Only confirm the artifact title and row count and direct the user to the rendered "
|
||||
"report displayed below. Keep the "
|
||||
"answer concise and business-readable."
|
||||
)
|
||||
for attempt in range(1, 3):
|
||||
@@ -4611,8 +5198,18 @@ def _render_assistant_message(
|
||||
message: Mapping[str, Any],
|
||||
message_key: str,
|
||||
) -> None:
|
||||
st.markdown(str(message.get("content") or ""))
|
||||
details = message.get("details")
|
||||
content = str(message.get("content") or "")
|
||||
if isinstance(details, Mapping):
|
||||
presentation_answer = _presentation_completion_answer(
|
||||
details.get("mcp_result", {}),
|
||||
details.get("agent_steps")
|
||||
if isinstance(details.get("agent_steps"), list)
|
||||
else None,
|
||||
)
|
||||
if presentation_answer:
|
||||
content = presentation_answer
|
||||
st.markdown(content)
|
||||
basis = message.get("basis")
|
||||
if isinstance(basis, list) and basis:
|
||||
display_records = _display_markdown_records(
|
||||
@@ -4894,7 +5491,15 @@ def _process_submitted_question(
|
||||
with processing_status:
|
||||
refresh_progress(5, "대화 문맥을 불러오고 있습니다.")
|
||||
step_started = perf_counter()
|
||||
conversation = load_chat_context(conversation_id)
|
||||
current_selected_user_id = (
|
||||
selected_token_preset.user_id
|
||||
if selected_token_preset is not None
|
||||
else ""
|
||||
)
|
||||
conversation = load_chat_context(
|
||||
conversation_id,
|
||||
selected_user_id=current_selected_user_id,
|
||||
)
|
||||
step_elapsed = perf_counter() - step_started
|
||||
refresh_progress(
|
||||
15,
|
||||
@@ -4909,6 +5514,7 @@ def _process_submitted_question(
|
||||
question=normalized_question,
|
||||
messages=conversation,
|
||||
model_profile_key=active_model_profile,
|
||||
selected_user_id=current_selected_user_id,
|
||||
)
|
||||
step_elapsed = perf_counter() - step_started
|
||||
refresh_progress(
|
||||
@@ -5031,6 +5637,11 @@ def _process_submitted_question(
|
||||
bearer_token=bearer_token,
|
||||
limit=int(limit),
|
||||
model_profile_key=reasoning_model_profile,
|
||||
selected_user_id=current_selected_user_id,
|
||||
initial_route_key=_route_key(
|
||||
selected_route.server_id,
|
||||
selected_route.tool.name,
|
||||
),
|
||||
progress_callback=on_agent_step,
|
||||
)
|
||||
selected_server = agent_result["server"]
|
||||
@@ -5345,6 +5956,13 @@ def _process_submitted_question(
|
||||
}
|
||||
refresh_progress(96, "원본 MCP 응답으로 결과를 구성했습니다.")
|
||||
|
||||
presentation_answer = _presentation_completion_answer(
|
||||
answer_source,
|
||||
agent_steps,
|
||||
)
|
||||
if presentation_answer:
|
||||
assistant_message["content"] = presentation_answer
|
||||
|
||||
pre_save_elapsed = perf_counter() - process_started
|
||||
record_execution_event(
|
||||
percent=98,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>HMM | 팀 포트폴리오 선사 실적</title>
|
||||
<style>
|
||||
:root { --hmm:#0065ad; --hmm-deep:#004a84; --ink:#102c43; --copy:#3d5363; --muted:#71818c; --line:#0d78c4; --pale:#edf7fc; --canvas:#f4f5f6; --green:#16815d; --amber:#b66b00; --red:#c5413c; font-family:"Noto Sans KR","Malgun Gothic",Arial,sans-serif; color:var(--ink); }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; min-width:320px; background:var(--canvas); }
|
||||
.page { min-height:100vh; max-width:1480px; margin:0 auto; background:#fff; box-shadow:0 0 40px rgba(12,38,60,.08); }
|
||||
.wordmark { display:flex; align-items:flex-end; gap:9px; font-size:18px; font-weight:900; letter-spacing:-.03em; }
|
||||
.wordmark::before { content:""; width:24px; height:21px; display:inline-block; background:linear-gradient(155deg,transparent 37%,#0571bc 38% 47%,transparent 48%),linear-gradient(26deg,transparent 42%,#0571bc 43% 52%,transparent 53%); border-left:2px solid #0571bc; border-bottom:2px solid #0571bc; }
|
||||
.report-name { margin:24px 0 31px; font-weight:800; font-size:13px; line-height:1.3; }
|
||||
.report-name span { display:block; color:var(--hmm); }
|
||||
.side-tools { padding:12px 0 22px; border-bottom:1px solid #8f969a; color:#056bad; font-size:16px; letter-spacing:6px; }
|
||||
nav { margin-top:22px; } .nav-group { padding:15px 0; border-bottom:1px solid #8f969a; }
|
||||
.nav-group-title { margin:0 0 11px; font-size:12px; font-weight:850; text-transform:uppercase; }
|
||||
.nav-item { display:block; padding:5px 9px; color:#69747b; font-size:11px; line-height:1.3; text-decoration:none; }
|
||||
.nav-item.active { color:#fff; background:linear-gradient(90deg,#0066ae,#52a9d9); font-weight:800; }
|
||||
.side-foot { margin-top:28px; color:#748087; font-size:10px; line-height:1.6; }
|
||||
.content { padding:42px min(6vw,92px) 45px; }
|
||||
.brand-banner { display:flex; align-items:center; justify-content:space-between; gap:18px; padding-bottom:18px; }
|
||||
.brand-banner img { display:block; width:128px; height:auto; }
|
||||
.brand-banner span { color:#627887; font-size:10px; font-weight:750; letter-spacing:.12em; text-transform:uppercase; }
|
||||
.top-line { height:4px; background:#045fa5; margin-bottom:32px; }
|
||||
.report-head { display:flex; justify-content:space-between; align-items:flex-start; gap:28px; padding-bottom:35px; border-bottom:1px solid var(--line); }
|
||||
.kicker { margin:0 0 10px; color:#0070ba; font-size:12px; font-weight:850; letter-spacing:.025em; }
|
||||
h1 { margin:0; color:#075b9f; font-size:clamp(30px,3.25vw,50px); line-height:1.16; letter-spacing:-.07em; font-weight:700; }
|
||||
h1 b { font-weight:850; }
|
||||
.head-meta { min-width:195px; padding-left:22px; border-left:1px solid #96c8e7; color:#647682; font-size:11px; line-height:1.65; }
|
||||
.head-meta strong { display:block; color:#075b9f; font-size:12px; }
|
||||
.intro { padding:18px 0 23px; color:var(--copy); font-size:15px; line-height:1.75; border-bottom:1px solid #8ac5e8; }
|
||||
.section-heading { margin:0 0 16px; color:#005fa9; font-size:21px; letter-spacing:-.05em; }
|
||||
.section-heading small { margin-left:8px; color:#71818c; font-size:11px; letter-spacing:0; font-weight:500; }
|
||||
.executive { display:grid; grid-template-columns:1.45fr 1fr; gap:42px; padding:29px 0 30px; border-bottom:1px solid var(--line); }
|
||||
.metrics { display:grid; grid-template-columns:repeat(2,1fr); border-top:2px solid #1478bb; border-left:1px solid #c8dce9; }
|
||||
.metric { min-height:111px; padding:17px 18px; border-right:1px solid #c8dce9; border-bottom:1px solid #c8dce9; }
|
||||
.metric-label { color:#5b6f7e; font-size:11px; font-weight:700; }.metric-value { margin:8px 0 5px; color:#075b9f; font-size:27px; letter-spacing:-.055em; font-weight:850; font-variant-numeric:tabular-nums; }.metric-value.money { font-size:23px; }.metric-note { color:#75848c; font-size:10px; }
|
||||
.risk-panel { padding:2px 0 0 25px; border-left:1px dotted #1478bb; }.risk-panel h2 { margin:0 0 15px; color:#005fa9; font-size:20px; letter-spacing:-.05em; }
|
||||
.risk-message { margin:0 0 17px; color:var(--copy); font-size:12px; line-height:1.65; }.risk-list { display:grid; gap:9px; }.risk-item { display:flex; align-items:center; gap:10px; padding-bottom:8px; border-bottom:1px solid #d7e8f3; font-size:11px; }.risk-item:last-child { border-bottom:0; }.risk-item-name { flex:1; font-weight:750; }.pill { padding:3px 7px; border-radius:2px; font-size:10px; font-weight:850; }.pill.red { color:var(--red); background:#fff1f0; }.pill.amber { color:var(--amber); background:#fff6e7; }.pill.green { color:var(--green); background:#eaf7f0; }
|
||||
.portfolio { padding:31px 0 28px; border-bottom:1px solid var(--line); }.portfolio-grid { display:grid; grid-template-columns:minmax(0,1.65fr) minmax(260px,.8fr); gap:43px; }.chart-note { margin:-8px 0 22px; color:#73838e; font-size:11px; }.bar-chart { display:grid; gap:12px; }.bar-row { display:grid; grid-template-columns:146px minmax(100px,1fr) 112px; align-items:center; gap:12px; }.bar-person { font-size:11px; }.bar-person b { display:block; color:#134f7f; font-size:12px; }.bar-person span { color:#788791; }.bar-lane { height:24px; background:#ebf2f6; overflow:hidden; }.bar { height:100%; min-width:4px; background:linear-gradient(90deg,#0073bb,#1aa2d8); position:relative; }.bar.critical { background:linear-gradient(90deg,#0073bb 0 84%,#d75349 84%); }.bar-value { color:#15486f; text-align:right; font-size:11px; font-weight:800; font-variant-numeric:tabular-nums; }.bar-value span { display:block; color:#72828c; font-size:9px; font-weight:500; }
|
||||
.chart-aside { padding:14px 0 0 22px; border-left:1px dotted #1478bb; }.chart-aside h3 { margin:0 0 14px; color:#005fa9; font-size:16px; }.legend { display:flex; justify-content:space-between; align-items:end; padding:10px 0; border-bottom:1px solid #d5e4ed; }.legend:last-child { border-bottom:0; }.legend-label { display:flex; align-items:center; gap:8px; font-size:11px; }.dot { width:10px; height:10px; border-radius:50%; }.dot.green { background:var(--green); }.dot.amber { background:var(--amber); }.dot.red { background:var(--red); }.legend strong { color:#075b9f; font-size:20px; }
|
||||
.detail { padding:31px 0 28px; }.detail-head { display:flex; justify-content:space-between; align-items:end; gap:16px; }.detail-head p { margin:0 0 16px; color:#75848c; font-size:11px; }.detail-table { width:100%; border-collapse:collapse; border-top:2px solid #1478bb; }.detail-table th { padding:11px 10px; background:#eff8fd; color:#176aa4; text-align:left; font-size:10px; font-weight:800; }.detail-table td { padding:12px 10px; border-bottom:1px solid #d4e3eb; color:#334f62; font-size:11px; }.detail-table .code { display:block; margin-bottom:2px; color:#75848c; font-size:9px; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }.detail-table .name { font-weight:750; }.number { text-align:right; font-variant-numeric:tabular-nums; }.negative { color:var(--red)!important; }.empty { padding:35px; color:#77868f; text-align:center; border:1px solid #d5e4ed; }
|
||||
.footnotes { display:grid; grid-template-columns:1.4fr 1fr; gap:25px; padding-top:19px; border-top:1px solid var(--line); color:#697d89; font-size:10px; line-height:1.7; }.footnotes h3 { margin:0 0 5px; color:#075b9f; font-size:11px; }.footnotes p,.footnotes ul { margin:0; padding-left:15px; }.footnotes p { padding-left:0; }
|
||||
@media(max-width:1000px){.content{padding:32px 35px 42px}.executive,.portfolio-grid{gap:25px}.bar-row{grid-template-columns:118px minmax(80px,1fr) 95px}}
|
||||
@media(max-width:760px){.content{padding:24px 18px 35px}.top-line{margin-bottom:20px}.report-head,.executive,.portfolio-grid,.footnotes{grid-template-columns:1fr;display:grid}.report-head{gap:17px;padding-bottom:24px}.head-meta{padding-left:0;border-left:0;border-top:1px solid #96c8e7;padding-top:10px}.intro{font-size:13px}.risk-panel,.chart-aside{padding:24px 0 0;border-left:0;border-top:1px dotted #1478bb}.bar-row{grid-template-columns:105px minmax(30px,1fr) 80px;gap:7px}.detail{overflow-x:auto}.detail-table{min-width:690px}.footnotes{gap:14px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="report-root" class="page" aria-live="polite"></main>
|
||||
<script>
|
||||
// 서버가 이미 권한 검사를 마친 조회 결과 JSON을 이 위치에 주입한다.
|
||||
const reportData = __REPORT_DATA__;
|
||||
const esc=(v)=>String(v??"").replace(/[&<>'"]/g,c=>({"&":"&","<":"<",">":">","'":"'","\"":"""}[c]));
|
||||
const n=(v,d=2)=>new Intl.NumberFormat("en-US",{maximumFractionDigits:d}).format(Number(v||0));
|
||||
const usd=(v)=>`${n(v)} USD`; const pct=(v)=>`${n(v)}%`; const when=(v)=>new Intl.DateTimeFormat("ko-KR",{dateStyle:"medium",timeStyle:"short",timeZone:"Asia/Seoul"}).format(new Date(v));
|
||||
const riskClass=(v)=>String(v||"").toLowerCase(); const riskLabel=(v)=>({GREEN:"정상",AMBER:"주의",RED:"위험"}[v]||v||"미분류");
|
||||
function aggregate(rows){ const risks={GREEN:0,AMBER:0,RED:0}; const people=new Map(); rows.forEach(row=>{const revenue=Number(row.latestRevenueUsd||0); const margin=Number(row.latestGrossMarginUsd||0); risks[row.latestRiskLevel]=(risks[row.latestRiskLevel]||0)+1; if(!people.has(row.employeeCode)) people.set(row.employeeCode,{code:row.employeeCode,name:row.employeeName,revenue:0,carriers:0,hasRisk:false}); const p=people.get(row.employeeCode);p.revenue+=revenue;p.carriers+=1;p.hasRisk||=row.latestRiskLevel==="RED"||row.latestRiskLevel==="AMBER";}); const totalRevenue=rows.reduce((s,r)=>s+Number(r.latestRevenueUsd||0),0); const totalMargin=rows.reduce((s,r)=>s+Number(r.latestGrossMarginUsd||0),0); return {risks,people:[...people.values()].sort((a,b)=>b.revenue-a.revenue),totalRevenue,totalMargin,avgReliability:rows.length?rows.reduce((s,r)=>s+Number(r.latestScheduleReliabilityPct||0),0)/rows.length:0}; }
|
||||
function badge(value){return `<span class="pill ${riskClass(value)}">${esc(riskLabel(value))}</span>`;}
|
||||
function detailRow(row){return `<tr><td><span class="code">${esc(row.employeeCode)}</span><span class="name">${esc(row.employeeName)}</span></td><td><span class="code">${esc(row.carrierCode)}</span><span class="name">${esc(row.carrierName)}</span></td><td class="number">${usd(row.latestRevenueUsd)}</td><td class="number ${Number(row.latestGrossMarginUsd)<0?"negative":""}">${usd(row.latestGrossMarginUsd)}</td><td class="number">${pct(row.latestScheduleReliabilityPct)}</td><td>${badge(row.latestRiskLevel)}</td></tr>`;}
|
||||
function renderHmmCarrierPerformanceReport(payload,target=document.getElementById("report-root")){const report=payload?.report||{};const rows=Array.isArray(payload?.rows)?payload.rows:[];const s=aggregate(rows);const max=Math.max(...s.people.map(p=>p.revenue),1);const watch=rows.filter(r=>r.latestRiskLevel!=="GREEN").sort((a,b)=>a.latestRiskLevel.localeCompare(b.latestRiskLevel));target.innerHTML=`
|
||||
<section class="content"><div class="brand-banner"><img src="https://eu-images.contentstack.com/v3/assets/bltdcfe6aab5515629e/bltaf50776e73f3149f/668ea7b97dc26754645e1830/hmmci.png?width=1400&auto=webp&quality=80&disable=upscale" alt="HMM"><span>HMM Management Report · Internal Demo</span></div><div class="top-line"></div><header class="report-head"><div><p class="kicker">${esc(report.id||"FEDERATION")} · ${esc(report.category||"HMM Business Intelligence")}</p><h1><b>${esc(report.title||"팀 포트폴리오")}</b> — 최신 선사 실적</h1></div><div class="head-meta"><strong>${esc(report.requestedBy||"-")} 팀장 조회</strong>생성 ${esc(when(report.generatedAt))}<br>MCP ${esc(report.execution?.calls||0)}회 호출<br>${esc(report.execution?.tool||"-")}</div></header>
|
||||
<p class="intro">${esc(report.answer||report.question||"조회된 선사 실적입니다.")} 전체 ${n(rows.length,0)}개 담당 선사의 매출·수익성·운항 지표를 담당자별 포트폴리오 관점에서 요약했습니다.</p>
|
||||
<section id="summary" class="executive"><div><h2 class="section-heading">핵심 요약 <small>Latest performance snapshot</small></h2><div class="metrics"><article class="metric"><div class="metric-label">담당 선사</div><div class="metric-value">${n(rows.length,0)}<small>개</small></div><div class="metric-note">팀원 ${n(s.people.length,0)}명 기준</div></article><article class="metric"><div class="metric-label">최신 매출 합계</div><div class="metric-value money">${usd(s.totalRevenue)}</div><div class="metric-note">담당 선사별 최신 기준월 합산</div></article><article class="metric"><div class="metric-label">매출총이익 합계</div><div class="metric-value money ${s.totalMargin<0?"negative":""}">${usd(s.totalMargin)}</div><div class="metric-note">음수 마진 선사 포함</div></article><article class="metric"><div class="metric-label">평균 정시 운항률</div><div class="metric-value">${pct(s.avgReliability)}</div><div class="metric-note">담당 선사 단순 평균</div></article></div></div><aside id="risk" class="risk-panel"><h2>위험 신호</h2><p class="risk-message">주의·위험 등급 선사 ${n(s.risks.AMBER+s.risks.RED,0)}개를 우선 점검 대상으로 표시합니다.</p><div class="risk-list">${watch.length?watch.map(r=>`<div class="risk-item">${badge(r.latestRiskLevel)}<span class="risk-item-name">${esc(r.carrierName)}</span><span>${esc(r.employeeName)}</span></div>`).join(""):'<div class="risk-item">현재 주의·위험 선사가 없습니다.</div>'}</div></aside></section>
|
||||
<section id="portfolio" class="portfolio"><h2 class="section-heading">담당자별 포트폴리오 매출 <small>Latest revenue by employee</small></h2><div class="portfolio-grid"><div><p class="chart-note">각 막대는 담당 선사 최신 매출의 합계입니다. 막대 끝의 색상은 해당 담당자 포트폴리오에 주의·위험 선사가 있는 경우를 나타냅니다.</p><div class="bar-chart">${s.people.map(p=>`<div class="bar-row"><div class="bar-person"><b>${esc(p.name)}</b><span>${esc(p.code)} · ${n(p.carriers,0)}개 선사</span></div><div class="bar-lane"><div class="bar ${p.hasRisk?"critical":""}" style="width:${(p.revenue/max*100).toFixed(2)}%"></div></div><div class="bar-value">${usd(p.revenue)}<span>팀 매출 ${(p.revenue/s.totalRevenue*100).toFixed(1)}%</span></div></div>`).join("")||'<div class="empty">차트 데이터가 없습니다.</div>'}</div></div><aside class="chart-aside"><h3>위험 등급 분포</h3><div class="legend"><span class="legend-label"><i class="dot green"></i>정상</span><strong>${n(s.risks.GREEN,0)}</strong></div><div class="legend"><span class="legend-label"><i class="dot amber"></i>주의</span><strong>${n(s.risks.AMBER,0)}</strong></div><div class="legend"><span class="legend-label"><i class="dot red"></i>위험</span><strong>${n(s.risks.RED,0)}</strong></div></aside></div></section>
|
||||
<section id="detail" class="detail"><div class="detail-head"><h2 class="section-heading">선사별 최신 지표 <small>Carrier detail</small></h2><p>총 ${n(rows.length,0)}건 · 최신순 1~${n(rows.length,0)}건 표시</p></div>${rows.length?`<table class="detail-table"><thead><tr><th>담당자</th><th>선사</th><th class="number">최신 매출</th><th class="number">매출총이익</th><th class="number">정시 운항률</th><th>위험 등급</th></tr></thead><tbody>${rows.map(detailRow).join("")}</tbody></table>`:'<div class="empty">표시할 상세 데이터가 없습니다.</div>'}</section>
|
||||
<footer id="notes" class="footnotes"><section><h3>답변 근거</h3><ul>${(report.evidence||[]).map(e=>`<li>${esc(e)}</li>`).join("")||'<li>제공된 근거가 없습니다.</li>'}</ul></section><section><h3>제약 및 주의</h3><p>${esc(report.limitation||"제약 정보가 제공되지 않았습니다.")}</p></section></footer></section>`;}
|
||||
window.renderHmmCarrierPerformanceReport=renderHmmCarrierPerformanceReport;renderHmmCarrierPerformanceReport(reportData);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -40,23 +40,37 @@
|
||||
{
|
||||
"id": "FED-01",
|
||||
"enabled": true,
|
||||
"category": "선사 실적 Federation",
|
||||
"title": "팀원별 담당 선사 최신 실적",
|
||||
"question": "E1001 팀장의 팀원별 담당 선사와 해당 선사의 최신 매출, 매출총이익, 정시 운항률, 위험 등급을 보여줘"
|
||||
"category": "선사 실적",
|
||||
"title": "우리 팀 담당 선사 최신 실적",
|
||||
"question": "우리 팀원별 담당 선사와 각 선사의 최신 매출, 매출총이익, 정시 운항률, 위험 등급을 보여줘"
|
||||
},
|
||||
{
|
||||
"id": "FED-02",
|
||||
"enabled": true,
|
||||
"category": "선사 실적 Federation",
|
||||
"title": "위험 선사와 담당자",
|
||||
"question": "E1001 팀에서 최신 위험 등급이 RED인 선사를 담당하는 직원, 선사명, 매출, 정시 운항률과 클레임 발생률을 보여줘"
|
||||
"category": "선사 실적",
|
||||
"title": "주의가 필요한 선사",
|
||||
"question": "우리 팀이 담당하는 선사 중 최신 위험 등급이 RED인 선사의 담당자, 선사명, 매출, 정시 운항률과 클레임 발생률을 보여줘"
|
||||
},
|
||||
{
|
||||
"id": "FED-03",
|
||||
"enabled": true,
|
||||
"category": "선사 실적 Federation",
|
||||
"title": "담당 선사 월별 추이",
|
||||
"question": "E1006 직원이 담당하는 선사의 월별 매출, 운송 물동량, 매출총이익과 위험 등급을 기준월 순서로 보여줘"
|
||||
"category": "선사 실적",
|
||||
"title": "내 담당 선사 월별 추이",
|
||||
"question": "내가 담당하는 선사의 월별 매출, 운송 물동량, 매출총이익과 위험 등급을 기준월 순서로 보여줘"
|
||||
},
|
||||
{
|
||||
"id": "FED-04",
|
||||
"enabled": true,
|
||||
"category": "선사 실적 리포트",
|
||||
"title": "우리 팀 선사 실적 리포트",
|
||||
"question": "우리 팀원별 담당 선사의 최신 매출, 매출총이익, 정시 운항률과 위험 등급을 HMM 리포트로 보여줘"
|
||||
},
|
||||
{
|
||||
"id": "FED-05",
|
||||
"enabled": true,
|
||||
"category": "선사 실적 리포트",
|
||||
"title": "내 담당 선사 실적 리포트",
|
||||
"question": "내 담당 선사의 최신 매출, 매출총이익, 정시 운항률과 위험 등급을 HMM 리포트로 보여줘"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"enabled": true,
|
||||
"provider": "hmm_compat_mcp",
|
||||
"transport": "http",
|
||||
"endpoint_url": "https://hmm-mcp.cloud-handson.com/mcp",
|
||||
"endpoint_url": "https://hmm-backoffice.cloud-handson.com/mcp",
|
||||
"auth_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"timeout_seconds_env": "AI_WEB_AGENT_CONSOLE_MCP_TIMEOUT_SECONDS",
|
||||
"default_tool": "search_hr_data",
|
||||
@@ -15,7 +15,8 @@
|
||||
"search_hr_data",
|
||||
"resolve_hr_term",
|
||||
"search_hr_policy",
|
||||
"search_carrier_performance"
|
||||
"search_carrier_performance",
|
||||
"render_hmm_carrier_report"
|
||||
],
|
||||
"description": "HMM HR knowledge, ADB employee assignment, and RDS carrier performance MCP server"
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
{
|
||||
"enabled": true,
|
||||
"default": true,
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN_E1001",
|
||||
"user_id": "E1001",
|
||||
"name": "Kim Minseo",
|
||||
"role": "HR Team Manager",
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN_E1002",
|
||||
"user_id": "E1002",
|
||||
"name": "Lee Jiwon",
|
||||
"role": "HR Operations Specialist",
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN_E1003",
|
||||
"user_id": "E1003",
|
||||
"name": "Park Dohyun",
|
||||
"role": "People Analytics Analyst",
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN_E1005",
|
||||
"user_id": "E1005",
|
||||
"name": "Han Seojun",
|
||||
"role": "Recruiting Specialist",
|
||||
@@ -41,7 +41,7 @@
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"mcp_token_env": "HMM_MCP_BEARER_TOKEN_E1007",
|
||||
"user_id": "E1007",
|
||||
"name": "Kang Minho",
|
||||
"role": "HR Coordinator",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import html
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Mapping
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -102,14 +107,30 @@ class DemoScenarioConfigTest(unittest.TestCase):
|
||||
self.assertTrue(all(item.question.strip() for item in scenarios))
|
||||
by_id = {item.scenario_id: item for item in scenarios}
|
||||
self.assertEqual(
|
||||
{"FED-01", "FED-02", "FED-03"},
|
||||
{"FED-01", "FED-02", "FED-03"} & set(by_id),
|
||||
{"FED-01", "FED-02", "FED-03", "FED-04", "FED-05"},
|
||||
{"FED-01", "FED-02", "FED-03", "FED-04", "FED-05"} & set(by_id),
|
||||
)
|
||||
self.assertTrue(
|
||||
all("선사" in by_id[scenario_id].question for scenario_id in (
|
||||
"FED-01", "FED-02", "FED-03"
|
||||
"FED-01", "FED-02", "FED-03", "FED-04", "FED-05"
|
||||
))
|
||||
)
|
||||
carrier_scenarios = [
|
||||
item for item in scenarios if item.scenario_id.startswith("FED-")
|
||||
]
|
||||
self.assertTrue(
|
||||
all(
|
||||
re.search(r"\bE\d{4,}\b", item.question, flags=re.IGNORECASE) is None
|
||||
for item in carrier_scenarios
|
||||
)
|
||||
)
|
||||
report_scenarios = [
|
||||
item for item in carrier_scenarios if "리포트로 보여줘" in item.question
|
||||
]
|
||||
self.assertGreaterEqual(len(report_scenarios), 2)
|
||||
self.assertTrue(
|
||||
all(item.category == "선사 실적 리포트" for item in report_scenarios)
|
||||
)
|
||||
|
||||
def test_hmm_mcp_allows_carrier_federation_tool(self) -> None:
|
||||
path = Path(__file__).parents[1] / "config" / "mcp_servers.json"
|
||||
@@ -123,6 +144,282 @@ class DemoScenarioConfigTest(unittest.TestCase):
|
||||
server["tool_allowlist"],
|
||||
)
|
||||
|
||||
def test_hmm_mcp_allows_dynamic_html_renderer(self) -> None:
|
||||
root = Path(__file__).parents[1]
|
||||
payload = json.loads(
|
||||
(root / "config" / "mcp_servers.json").read_text(encoding="utf-8")
|
||||
)
|
||||
server = next(
|
||||
item for item in payload["servers"] if item["id"] == "hmm_hr_mcp"
|
||||
)
|
||||
source = (root / "app.py").read_text(encoding="utf-8")
|
||||
|
||||
self.assertEqual(
|
||||
server["endpoint_url"],
|
||||
"https://hmm-backoffice.cloud-handson.com/mcp",
|
||||
)
|
||||
self.assertIn("render_hmm_carrier_report", server["tool_allowlist"])
|
||||
self.assertNotIn('tool.name == "render_hmm_carrier_report"', source)
|
||||
|
||||
def test_hmm_report_rows_accept_nested_select_ai_json_array(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helper = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name == "_mcp_structured_rows"
|
||||
)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"Mapping": Mapping,
|
||||
"json": json,
|
||||
}
|
||||
exec(compile(ast.Module(body=[helper], type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
rows = namespace["_mcp_structured_rows"](
|
||||
{
|
||||
"response": {
|
||||
"result": json.dumps(
|
||||
[
|
||||
{"EMPLOYEE_CODE": "E9001", "CARRIER_CODE": "C901"},
|
||||
{"EMPLOYEE_CODE": "E9002", "CARRIER_CODE": "C902"},
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(len(rows), 2)
|
||||
self.assertEqual(rows[0]["CARRIER_CODE"], "C901")
|
||||
|
||||
def test_hmm_report_normalizes_repeated_select_ai_column_labels(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helpers = [
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name in {"_camel_case_key", "_normalize_presentation_value"}
|
||||
]
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"Mapping": Mapping,
|
||||
"re": re,
|
||||
}
|
||||
exec(compile(ast.Module(body=helpers, type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
first = namespace["_normalize_presentation_value"](
|
||||
{"CARRIER_CODE": "C001", "LATEST_REVENUE_USD": 100}
|
||||
)
|
||||
repeated = namespace["_normalize_presentation_value"](
|
||||
{"carrier Code": "C002", "LATEST REVENUE USD": 200}
|
||||
)
|
||||
|
||||
self.assertEqual(first, {"carrierCode": "C001", "latestRevenueUsd": 100})
|
||||
self.assertEqual(repeated, {"carrierCode": "C002", "latestRevenueUsd": 200})
|
||||
|
||||
def test_hmm_report_title_and_answer_follow_presentation_contract(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helper = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name == "_clean_presentation_title"
|
||||
)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"html": html,
|
||||
"re": re,
|
||||
}
|
||||
exec(compile(ast.Module(body=[helper], type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
title = namespace["_clean_presentation_title"](
|
||||
"<b>E1001 팀 포트폴리오</b>"
|
||||
)
|
||||
|
||||
self.assertEqual(title, "E1001 팀 포트폴리오")
|
||||
self.assertIn('"title": _clean_presentation_title(title)', source)
|
||||
self.assertIn(
|
||||
'assistant_message["content"] = presentation_answer',
|
||||
source,
|
||||
)
|
||||
self.assertIn(
|
||||
"presentation_answer = _presentation_completion_answer(",
|
||||
source,
|
||||
)
|
||||
self.assertIn(
|
||||
"do not reproduce HTML tags, Markdown tables",
|
||||
source,
|
||||
)
|
||||
|
||||
def test_chat_context_is_scoped_to_current_selected_user(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helper = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name == "load_chat_context"
|
||||
)
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
class FakeConnection:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args):
|
||||
return False
|
||||
|
||||
def execute(self, sql, params):
|
||||
captured["sql"] = sql
|
||||
captured["params"] = params
|
||||
return self
|
||||
|
||||
def fetchall(self):
|
||||
return [{"question": "내 담당 선사", "answer": "2건"}]
|
||||
|
||||
namespace: dict[str, Any] = {
|
||||
"CHAT_CONTEXT_TURNS": 8,
|
||||
"MAX_CONVERSATION_MESSAGES": 16,
|
||||
"_chat_db_connect": FakeConnection,
|
||||
"_is_failed_synthesis_answer": lambda _value: False,
|
||||
}
|
||||
exec(compile(ast.Module(body=[helper], type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
messages = namespace["load_chat_context"](
|
||||
"conversation-1",
|
||||
selected_user_id="E1002",
|
||||
)
|
||||
|
||||
self.assertIn("selected_user_id = ?", captured["sql"])
|
||||
self.assertEqual(
|
||||
captured["params"],
|
||||
("conversation-1", "E1002", "E1002", 8),
|
||||
)
|
||||
self.assertEqual(messages[0]["content"], "내 담당 선사")
|
||||
|
||||
def test_standalone_question_uses_current_user_without_prior_context(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helpers = [
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name in {"_conversation_context", "resolve_standalone_question"}
|
||||
]
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
class FakeClient:
|
||||
def complete(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return json.dumps(
|
||||
{
|
||||
"standalone_question": (
|
||||
"E1002 사용자의 담당 선사 최신 실적을 조회해줘"
|
||||
)
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"Mapping": Mapping,
|
||||
"MAX_CONVERSATION_MESSAGES": 16,
|
||||
"json": json,
|
||||
"resolve_model_profile": lambda _key: SimpleNamespace(
|
||||
model_id="model",
|
||||
answer_model_region="region",
|
||||
answer_model_endpoint="endpoint",
|
||||
),
|
||||
"build_oci_genai_completion_client": lambda *_args: FakeClient(),
|
||||
"temperature_for_model_profile": lambda _profile: 0.0,
|
||||
}
|
||||
exec(compile(ast.Module(body=helpers, type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
rewritten = namespace["resolve_standalone_question"](
|
||||
question="내 담당 선사 최신 실적을 리포트로 보여줘",
|
||||
messages=[],
|
||||
model_profile_key="test",
|
||||
selected_user_id="E1002",
|
||||
)
|
||||
prompt_payload = json.loads(captured["user_prompt"])
|
||||
|
||||
self.assertTrue(rewritten.startswith("E1002"))
|
||||
self.assertEqual(prompt_payload["current_selected_user_id"], "E1002")
|
||||
self.assertIn("authoritative", captured["system_prompt"])
|
||||
|
||||
def test_report_payload_requester_prefers_current_selected_user(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helper = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name == "_presentation_payload"
|
||||
)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"Mapping": Mapping,
|
||||
"datetime": __import__("datetime").datetime,
|
||||
"timezone": __import__("datetime").timezone,
|
||||
"re": re,
|
||||
"_mcp_structured_rows": lambda _value: [],
|
||||
"_normalize_presentation_value": lambda value: value,
|
||||
"_clean_presentation_title": lambda value: str(value),
|
||||
}
|
||||
exec(compile(ast.Module(body=[helper], type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
payload = namespace["_presentation_payload"](
|
||||
"E1001 팀장 문맥이 남은 질문",
|
||||
[],
|
||||
title="담당 선사 실적",
|
||||
selected_user_id="E1002",
|
||||
)
|
||||
|
||||
self.assertEqual(payload["report"]["requestedBy"], "E1002")
|
||||
|
||||
def test_hmm_report_data_query_drops_html_format_request(self) -> None:
|
||||
source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
helper = next(
|
||||
node
|
||||
for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef)
|
||||
and node.name == "_fallback_presentation_data_query"
|
||||
)
|
||||
namespace: dict[str, Any] = {"re": re}
|
||||
exec(compile(ast.Module(body=[helper], type_ignores=[]), "app.py", "exec"), namespace)
|
||||
|
||||
query = namespace["_fallback_presentation_data_query"](
|
||||
"E1001 팀장의 담당 선사 최신 매출, 매출총이익, 정시 운항률, "
|
||||
"위험 등급을 HTML로 보여줘"
|
||||
)
|
||||
|
||||
self.assertNotIn("HTML", query.upper())
|
||||
self.assertIn("E1001", query)
|
||||
self.assertIn("매출총이익", query)
|
||||
self.assertIn("정시 운항률", query)
|
||||
self.assertIn("위험 등급", query)
|
||||
self.assertIn("_mcp_rows_contain_presentation_markup(mcp_result)", source)
|
||||
|
||||
personal_query = namespace["_fallback_presentation_data_query"](
|
||||
"내 담당 선사와 최신 매출을 리포트로 보여줘"
|
||||
)
|
||||
self.assertEqual(personal_query, "내 담당 선사와 최신 매출을 보여줘")
|
||||
|
||||
def test_hmm_report_template_contains_only_dynamic_payload_slot(self) -> None:
|
||||
template = (
|
||||
Path(__file__).parents[1]
|
||||
/ "assets"
|
||||
/ "hmm-carrier-performance-report.html"
|
||||
).read_text(encoding="utf-8")
|
||||
|
||||
self.assertEqual(template.count("__REPORT_DATA__"), 1)
|
||||
self.assertNotIn("Bluewave Maritime", template)
|
||||
self.assertNotIn("Southern Cross Marine", template)
|
||||
|
||||
def test_hmm_demo_user_presets_reference_runtime_token_only(self) -> None:
|
||||
path = Path(__file__).parents[1] / "config" / "vpd_token_presets.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
@@ -132,7 +429,10 @@ class DemoScenarioConfigTest(unittest.TestCase):
|
||||
self.assertEqual({item["user_id"] for item in presets}, {
|
||||
"E1001", "E1002", "E1003", "E1005", "E1007"
|
||||
})
|
||||
self.assertTrue(all(item["mcp_token_env"] == "HMM_MCP_BEARER_TOKEN" for item in presets))
|
||||
self.assertEqual(
|
||||
{item["mcp_token_env"] for item in presets},
|
||||
{f"HMM_MCP_BEARER_TOKEN_{item['user_id']}" for item in presets},
|
||||
)
|
||||
self.assertTrue(all("token" not in item for item in presets))
|
||||
|
||||
def test_duplicate_id_is_rejected(self) -> None:
|
||||
|
||||
159
database/adb/47_dds_ad_identity_test_setup.sql
Normal file
159
database/adb/47_dds_ad_identity_test_setup.sql
Normal file
@@ -0,0 +1,159 @@
|
||||
-- ============================================================
|
||||
-- 47_dds_ad_identity_test_setup.sql
|
||||
--
|
||||
-- Test-only bridge for the isolated dds.test Active Directory domain.
|
||||
-- Maps immutable AD objectGUID values to the existing HMM application users
|
||||
-- 1 and 2, then publishes only their passwordless local DDS END USERs.
|
||||
--
|
||||
-- This does NOT validate an AD/OIDC JWT. A verified issuer + subject must be
|
||||
-- resolved by the MCP application before it uses this bridge.
|
||||
-- ============================================================
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE
|
||||
SET ECHO OFF
|
||||
SET FEEDBACK ON
|
||||
SET DEFINE OFF
|
||||
|
||||
PROMPT === 1. Creating external identity bridge ===
|
||||
BEGIN
|
||||
EXECUTE IMMEDIATE q'[
|
||||
CREATE TABLE cb_external_identity_binding (
|
||||
issuer VARCHAR2(512) NOT NULL,
|
||||
subject VARCHAR2(512) NOT NULL,
|
||||
application_user_id NUMBER NOT NULL,
|
||||
display_name VARCHAR2(256),
|
||||
active CHAR(1) DEFAULT 'Y' NOT NULL
|
||||
CHECK (active IN ('Y', 'N')),
|
||||
created_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
|
||||
CONSTRAINT cb_external_identity_binding_pk PRIMARY KEY (issuer, subject)
|
||||
)]';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
IF SQLCODE <> -955 THEN RAISE; END IF;
|
||||
END;
|
||||
/
|
||||
|
||||
BEGIN
|
||||
EXECUTE IMMEDIATE 'CREATE INDEX cb_external_identity_binding_user_ix '
|
||||
|| 'ON cb_external_identity_binding (application_user_id)';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
IF SQLCODE <> -955 THEN RAISE; END IF;
|
||||
END;
|
||||
/
|
||||
|
||||
PROMPT === 2. Creating DDS END USER map ===
|
||||
BEGIN
|
||||
EXECUTE IMMEDIATE q'[
|
||||
CREATE TABLE cb_dds_end_user_map (
|
||||
application_user_id NUMBER PRIMARY KEY,
|
||||
end_user_name VARCHAR2(128) NOT NULL UNIQUE,
|
||||
data_role_name VARCHAR2(128) NOT NULL UNIQUE,
|
||||
lookup_key_ref VARCHAR2(128) NOT NULL,
|
||||
grant_name VARCHAR2(128) NOT NULL,
|
||||
publish_status VARCHAR2(20) NOT NULL
|
||||
CHECK (publish_status IN ('PENDING', 'PUBLISHED', 'REVOKED', 'FAILED')),
|
||||
published_at TIMESTAMP,
|
||||
last_error VARCHAR2(1000)
|
||||
)]';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
IF SQLCODE <> -955 THEN RAISE; END IF;
|
||||
END;
|
||||
/
|
||||
|
||||
DECLARE
|
||||
v_active_users NUMBER;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO v_active_users
|
||||
FROM cb_app_user
|
||||
WHERE user_id IN (1, 2) AND active = 'Y';
|
||||
IF v_active_users <> 2 THEN
|
||||
RAISE_APPLICATION_ERROR(-20947, 'Expected active HMM application users 1 and 2.');
|
||||
END IF;
|
||||
END;
|
||||
/
|
||||
|
||||
PROMPT === 3. Binding dds.test immutable subjects to HMM users ===
|
||||
MERGE INTO cb_external_identity_binding target
|
||||
USING (
|
||||
SELECT 'urn:dds-ad:test' AS issuer,
|
||||
'fa7ebe4b-aca8-4049-a436-7f3da2d27a9f' AS subject,
|
||||
1 AS application_user_id,
|
||||
'dds-alice' AS display_name
|
||||
FROM dual
|
||||
UNION ALL
|
||||
SELECT 'urn:dds-ad:test',
|
||||
'128546cf-ec0a-4e99-8f51-dfce29280c91',
|
||||
2,
|
||||
'dds-bob'
|
||||
FROM dual
|
||||
) source
|
||||
ON (target.issuer = source.issuer AND target.subject = source.subject)
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
target.application_user_id = source.application_user_id,
|
||||
target.display_name = source.display_name,
|
||||
target.active = 'Y',
|
||||
target.updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
issuer, subject, application_user_id, display_name, active
|
||||
) VALUES (
|
||||
source.issuer, source.subject, source.application_user_id, source.display_name, 'Y'
|
||||
);
|
||||
|
||||
MERGE INTO cb_dds_end_user_map target
|
||||
USING (
|
||||
SELECT user_id AS application_user_id,
|
||||
'DDS_U_' || TO_CHAR(user_id) AS end_user_name,
|
||||
'DDS_U_' || TO_CHAR(user_id) || '_ROLE' AS data_role_name,
|
||||
'DDS_OCI_IAM_CLIENT_SECRET_DERIVED_V1' AS lookup_key_ref,
|
||||
'DDS_MCP_U_' || TO_CHAR(user_id) || '_VECTOR_GRANT' AS grant_name
|
||||
FROM cb_app_user
|
||||
WHERE user_id IN (1, 2)
|
||||
) source
|
||||
ON (target.application_user_id = source.application_user_id)
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
target.end_user_name = source.end_user_name,
|
||||
target.data_role_name = source.data_role_name,
|
||||
target.lookup_key_ref = source.lookup_key_ref,
|
||||
target.grant_name = source.grant_name,
|
||||
target.publish_status = 'PENDING',
|
||||
target.last_error = NULL
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
application_user_id, end_user_name, data_role_name, lookup_key_ref,
|
||||
grant_name, publish_status
|
||||
) VALUES (
|
||||
source.application_user_id, source.end_user_name, source.data_role_name,
|
||||
source.lookup_key_ref, source.grant_name, 'PENDING'
|
||||
);
|
||||
|
||||
PROMPT === 4. Publishing DDS identities only (default deny until data grants exist) ===
|
||||
BEGIN
|
||||
FOR mapped_user IN (
|
||||
SELECT application_user_id, end_user_name, data_role_name
|
||||
FROM cb_dds_end_user_map
|
||||
WHERE application_user_id IN (1, 2)
|
||||
ORDER BY application_user_id
|
||||
) LOOP
|
||||
EXECUTE IMMEDIATE 'CREATE END USER IF NOT EXISTS "' || mapped_user.end_user_name || '"';
|
||||
EXECUTE IMMEDIATE 'CREATE DATA ROLE IF NOT EXISTS ' || mapped_user.data_role_name;
|
||||
EXECUTE IMMEDIATE 'GRANT DATA ROLE ' || mapped_user.data_role_name
|
||||
|| ' TO "' || mapped_user.end_user_name || '"';
|
||||
UPDATE cb_dds_end_user_map
|
||||
SET publish_status = 'PUBLISHED', published_at = SYSTIMESTAMP, last_error = NULL
|
||||
WHERE application_user_id = mapped_user.application_user_id;
|
||||
END LOOP;
|
||||
COMMIT;
|
||||
END;
|
||||
/
|
||||
|
||||
PROMPT === 5. Identity bridge inventory ===
|
||||
SELECT b.issuer, b.subject, b.display_name, b.application_user_id,
|
||||
m.end_user_name, m.data_role_name, m.publish_status
|
||||
FROM cb_external_identity_binding b
|
||||
JOIN cb_dds_end_user_map m ON m.application_user_id = b.application_user_id
|
||||
WHERE b.issuer = 'urn:dds-ad:test'
|
||||
ORDER BY b.application_user_id;
|
||||
|
||||
PROMPT === AD identity to DDS END USER test setup complete ===
|
||||
EXIT;
|
||||
72
database/adb/83_hmm_carrier_html_report_tool.sql
Normal file
72
database/adb/83_hmm_carrier_html_report_tool.sql
Normal file
@@ -0,0 +1,72 @@
|
||||
-- HMM carrier report template storage and DBMS_CLOUD_AI_AGENT custom tool.
|
||||
-- Run as ADMIN. Load the approved HTML template into HMM_REPORT_TEMPLATES
|
||||
-- through the deployment loader before enabling the MCP tool.
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK
|
||||
SET DEFINE OFF
|
||||
|
||||
CREATE TABLE hmm_report_templates (
|
||||
template_key VARCHAR2(64) PRIMARY KEY,
|
||||
template_version VARCHAR2(32) NOT NULL,
|
||||
html_template CLOB NOT NULL,
|
||||
active_yn CHAR(1) DEFAULT 'Y' NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
|
||||
CONSTRAINT hmm_report_templates_active_ck CHECK (active_yn IN ('Y', 'N'))
|
||||
);
|
||||
|
||||
CREATE OR REPLACE PACKAGE hmm_report_render_pkg AUTHID DEFINER AS
|
||||
FUNCTION render_carrier_report(p_report_json IN CLOB) RETURN CLOB;
|
||||
END hmm_report_render_pkg;
|
||||
/
|
||||
|
||||
CREATE OR REPLACE PACKAGE BODY hmm_report_render_pkg AS
|
||||
FUNCTION render_carrier_report(p_report_json IN CLOB) RETURN CLOB IS
|
||||
l_template CLOB;
|
||||
l_data CLOB;
|
||||
l_html VARCHAR2(32767);
|
||||
l_result CLOB;
|
||||
BEGIN
|
||||
IF p_report_json IS NULL OR dbms_lob.getlength(p_report_json) > 64000 THEN
|
||||
raise_application_error(-20101, 'Invalid report payload size.');
|
||||
END IF;
|
||||
IF NOT json_exists(p_report_json, '$.report') OR NOT json_exists(p_report_json, '$.rows') THEN
|
||||
raise_application_error(-20102, 'Report payload requires report and rows.');
|
||||
END IF;
|
||||
SELECT html_template INTO l_template
|
||||
FROM hmm_report_templates
|
||||
WHERE template_key = 'hmm-carrier-performance'
|
||||
AND active_yn = 'Y';
|
||||
l_data := replace(p_report_json, '</', '<\/');
|
||||
l_html := dbms_lob.substr(replace(l_template, '__REPORT_DATA__', l_data), 32767, 1);
|
||||
SELECT json_object(
|
||||
'status' VALUE 'ok',
|
||||
'template' VALUE 'hmm-carrier-performance',
|
||||
'html' VALUE l_html
|
||||
RETURNING CLOB
|
||||
) INTO l_result FROM dual;
|
||||
RETURN l_result;
|
||||
EXCEPTION
|
||||
WHEN no_data_found THEN
|
||||
raise_application_error(-20103, 'Active report template is not installed.');
|
||||
END render_carrier_report;
|
||||
END hmm_report_render_pkg;
|
||||
/
|
||||
|
||||
BEGIN
|
||||
DBMS_CLOUD_AI_AGENT.DROP_TOOL('HMM_CARRIER_REPORT_RENDERER', force => TRUE);
|
||||
DBMS_CLOUD_AI_AGENT.CREATE_TOOL(
|
||||
tool_name => 'HMM_CARRIER_REPORT_RENDERER',
|
||||
attributes => q'~{
|
||||
"instruction": "Render the supplied carrier-performance payload with the approved HMM HTML template. Do not query data and do not alter the supplied values.",
|
||||
"function": "HMM_REPORT_RENDER_PKG.RENDER_CARRIER_REPORT",
|
||||
"tool_inputs": [{"name":"P_REPORT_JSON","description":"Normalized carrier performance report JSON."}]
|
||||
}~',
|
||||
status => 'ENABLED',
|
||||
description => 'Renders approved HMM carrier-performance HTML from already-authorized query results.'
|
||||
);
|
||||
END;
|
||||
/
|
||||
|
||||
SELECT tool_name, status
|
||||
FROM user_ai_agent_tools
|
||||
WHERE tool_name = 'HMM_CARRIER_REPORT_RENDERER';
|
||||
323
database/adb/84_hmm_carrier_team_vpd.sql
Normal file
323
database/adb/84_hmm_carrier_team_vpd.sql
Normal file
@@ -0,0 +1,323 @@
|
||||
-- ============================================================
|
||||
-- 84_hmm_carrier_team_vpd.sql
|
||||
--
|
||||
-- Row security for HMM_CARRIER_ASSIGNMENTS_V:
|
||||
-- HMM_HR_VIEWER -> current employee only
|
||||
-- HMM_HR_MANAGER -> current employee and direct reports
|
||||
-- HMM_HR_ADMIN -> all assignments
|
||||
--
|
||||
-- Run as ADMIN after 72_hmm_leave_team_vpd.sql and
|
||||
-- 81_hmm_carrier_access_groups.sql. Plain bearer tokens are
|
||||
-- never stored by this script.
|
||||
-- ============================================================
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE
|
||||
SET ECHO OFF
|
||||
SET FEEDBACK ON
|
||||
SET DEFINE OFF
|
||||
|
||||
PROMPT === 1. Registering the protected carrier object ===
|
||||
DECLARE
|
||||
v_object_id NUMBER;
|
||||
BEGIN
|
||||
BEGIN
|
||||
SELECT object_id
|
||||
INTO v_object_id
|
||||
FROM hmm_access_objects
|
||||
WHERE owner = 'ADMIN'
|
||||
AND object_name = 'HMM_CARRIER_ASSIGNMENTS_V';
|
||||
|
||||
UPDATE hmm_access_objects
|
||||
SET enabled_yn = 'Y',
|
||||
description = 'Employee-to-carrier assignments protected by employee hierarchy',
|
||||
ords_path = 'cb-ords/cb-object-query/admin/hmm_carrier_assignments_v'
|
||||
WHERE object_id = v_object_id;
|
||||
EXCEPTION
|
||||
WHEN NO_DATA_FOUND THEN
|
||||
SELECT NVL(MAX(object_id), 0) + 1
|
||||
INTO v_object_id
|
||||
FROM hmm_access_objects;
|
||||
|
||||
INSERT INTO hmm_access_objects (
|
||||
object_id, owner, object_name, ords_path, enabled_yn, description
|
||||
) VALUES (
|
||||
v_object_id,
|
||||
'ADMIN',
|
||||
'HMM_CARRIER_ASSIGNMENTS_V',
|
||||
'cb-ords/cb-object-query/admin/hmm_carrier_assignments_v',
|
||||
'Y',
|
||||
'Employee-to-carrier assignments protected by employee hierarchy'
|
||||
);
|
||||
END;
|
||||
|
||||
FOR c IN (
|
||||
SELECT column_name
|
||||
FROM user_tab_columns
|
||||
WHERE table_name = 'HMM_CARRIER_ASSIGNMENTS_V'
|
||||
ORDER BY column_id
|
||||
) LOOP
|
||||
MERGE INTO hmm_access_object_columns dst
|
||||
USING (
|
||||
SELECT v_object_id object_id, c.column_name column_name FROM dual
|
||||
) src
|
||||
ON (dst.object_id = src.object_id AND dst.column_name = src.column_name)
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
column_id, object_id, column_name, sensitive_yn,
|
||||
sensitivity_level, redaction_method
|
||||
) VALUES (
|
||||
(SELECT NVL(MAX(column_id), 0) + 1 FROM hmm_access_object_columns),
|
||||
src.object_id, src.column_name, 'N', 'PUBLIC', 'NONE'
|
||||
);
|
||||
END LOOP;
|
||||
END;
|
||||
/
|
||||
|
||||
PROMPT === 2. Registering role rules ===
|
||||
DECLARE
|
||||
PROCEDURE ensure_permission(
|
||||
p_role_name IN VARCHAR2,
|
||||
p_rule_type IN VARCHAR2
|
||||
) AS
|
||||
v_role_id NUMBER;
|
||||
v_perm_id NUMBER;
|
||||
BEGIN
|
||||
SELECT role_id
|
||||
INTO v_role_id
|
||||
FROM hmm_access_roles
|
||||
WHERE role_name = p_role_name
|
||||
AND active_yn = 'Y';
|
||||
|
||||
BEGIN
|
||||
SELECT perm_id
|
||||
INTO v_perm_id
|
||||
FROM hmm_access_permissions
|
||||
WHERE role_id = v_role_id
|
||||
AND target_name = 'HMM_CARRIER_ASSIGNMENTS_V'
|
||||
AND action_name = 'SELECT';
|
||||
|
||||
UPDATE hmm_access_permissions
|
||||
SET permission_effect = 'ALLOW'
|
||||
WHERE perm_id = v_perm_id;
|
||||
EXCEPTION
|
||||
WHEN NO_DATA_FOUND THEN
|
||||
SELECT cb_permission_seq.NEXTVAL INTO v_perm_id FROM dual;
|
||||
INSERT INTO hmm_access_permissions (
|
||||
perm_id, role_id, target_name, action_name, permission_effect
|
||||
) VALUES (
|
||||
v_perm_id, v_role_id, 'HMM_CARRIER_ASSIGNMENTS_V', 'SELECT', 'ALLOW'
|
||||
);
|
||||
END;
|
||||
|
||||
DELETE FROM hmm_access_permission_rules WHERE perm_id = v_perm_id;
|
||||
INSERT INTO hmm_access_permission_rules (
|
||||
rule_id, perm_id, rule_column, rule_type, rule_value
|
||||
) VALUES (
|
||||
cb_permission_rule_seq.NEXTVAL,
|
||||
v_perm_id,
|
||||
'EMPLOYEE_ID',
|
||||
p_rule_type,
|
||||
NULL
|
||||
);
|
||||
END;
|
||||
BEGIN
|
||||
ensure_permission('HMM_HR_VIEWER', 'SELF');
|
||||
ensure_permission('HMM_HR_MANAGER', 'MANAGED_TEAM');
|
||||
ensure_permission('HMM_HR_ADMIN', 'ALL');
|
||||
END;
|
||||
/
|
||||
|
||||
COMMIT;
|
||||
|
||||
PROMPT === 3. Creating the carrier VPD predicate ===
|
||||
CREATE OR REPLACE FUNCTION hmm_carrier_vpd_filter(
|
||||
p_schema IN VARCHAR2,
|
||||
p_object IN VARCHAR2
|
||||
) RETURN VARCHAR2
|
||||
AUTHID DEFINER
|
||||
AS
|
||||
v_employee_id NUMBER;
|
||||
v_all_rule NUMBER := 0;
|
||||
v_team_rule NUMBER := 0;
|
||||
v_self_rule NUMBER := 0;
|
||||
BEGIN
|
||||
IF UPPER(TRIM(p_schema)) != 'ADMIN'
|
||||
OR UPPER(TRIM(p_object)) != 'HMM_CARRIER_ASSIGNMENTS_V' THEN
|
||||
RETURN '1 = 0';
|
||||
END IF;
|
||||
|
||||
BEGIN
|
||||
v_employee_id := TO_NUMBER(
|
||||
SYS_CONTEXT('HMM_ACCESS_CTX', 'EMPLOYEE_ID')
|
||||
);
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
RETURN '1 = 0';
|
||||
END;
|
||||
|
||||
IF v_employee_id IS NULL THEN
|
||||
RETURN '1 = 0';
|
||||
END IF;
|
||||
|
||||
SELECT NVL(MAX(CASE WHEN rule.rule_type = 'ALL' THEN 1 ELSE 0 END), 0),
|
||||
NVL(MAX(CASE WHEN rule.rule_type = 'MANAGED_TEAM' THEN 1 ELSE 0 END), 0),
|
||||
NVL(MAX(CASE WHEN rule.rule_type = 'SELF' THEN 1 ELSE 0 END), 0)
|
||||
INTO v_all_rule, v_team_rule, v_self_rule
|
||||
FROM (
|
||||
SELECT employee_role.role_id
|
||||
FROM hmm_employee_access_roles employee_role
|
||||
WHERE employee_role.employee_id = v_employee_id
|
||||
UNION
|
||||
SELECT group_role.role_id
|
||||
FROM hmm_access_group_members group_member
|
||||
JOIN hmm_access_groups access_group
|
||||
ON access_group.group_id = group_member.group_id
|
||||
AND access_group.active_yn = 'Y'
|
||||
JOIN hmm_group_access_roles group_role
|
||||
ON group_role.group_id = group_member.group_id
|
||||
WHERE group_member.employee_id = v_employee_id
|
||||
) effective_role
|
||||
JOIN hmm_access_roles role
|
||||
ON role.role_id = effective_role.role_id
|
||||
AND role.active_yn = 'Y'
|
||||
JOIN hmm_access_permissions permission
|
||||
ON permission.role_id = role.role_id
|
||||
AND permission.target_name = 'HMM_CARRIER_ASSIGNMENTS_V'
|
||||
AND permission.action_name = 'SELECT'
|
||||
AND permission.permission_effect = 'ALLOW'
|
||||
JOIN hmm_access_permission_rules rule
|
||||
ON rule.perm_id = permission.perm_id
|
||||
AND UPPER(TRIM(rule.rule_column)) = 'EMPLOYEE_ID';
|
||||
|
||||
IF v_all_rule = 1 THEN
|
||||
RETURN '1 = 1';
|
||||
END IF;
|
||||
|
||||
IF v_team_rule = 1 THEN
|
||||
RETURN 'EMPLOYEE_ID IN ('
|
||||
|| 'SELECT employee.employee_id '
|
||||
|| 'FROM ADMIN.HMM_HR_EMPLOYEES employee '
|
||||
|| 'WHERE employee.employee_id = '
|
||||
|| 'TO_NUMBER(SYS_CONTEXT(''HMM_ACCESS_CTX'', ''EMPLOYEE_ID'')) '
|
||||
|| 'OR employee.manager_employee_id = '
|
||||
|| 'TO_NUMBER(SYS_CONTEXT(''HMM_ACCESS_CTX'', ''EMPLOYEE_ID''))'
|
||||
|| ')';
|
||||
END IF;
|
||||
|
||||
IF v_self_rule = 1 THEN
|
||||
RETURN 'EMPLOYEE_ID = TO_NUMBER('
|
||||
|| 'SYS_CONTEXT(''HMM_ACCESS_CTX'', ''EMPLOYEE_ID''))';
|
||||
END IF;
|
||||
|
||||
RETURN '1 = 0';
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
RETURN '1 = 0';
|
||||
END;
|
||||
/
|
||||
|
||||
SHOW ERRORS FUNCTION hmm_carrier_vpd_filter
|
||||
|
||||
PROMPT === 4. Attaching the VPD policy ===
|
||||
BEGIN
|
||||
BEGIN
|
||||
DBMS_RLS.DROP_POLICY(
|
||||
object_schema => 'ADMIN',
|
||||
object_name => 'HMM_CARRIER_ASSIGNMENTS_V',
|
||||
policy_name => 'HMM_CARRIER_SCOPE_POLICY'
|
||||
);
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
IF SQLCODE != -28102 THEN
|
||||
RAISE;
|
||||
END IF;
|
||||
END;
|
||||
|
||||
DBMS_RLS.ADD_POLICY(
|
||||
object_schema => 'ADMIN',
|
||||
object_name => 'HMM_CARRIER_ASSIGNMENTS_V',
|
||||
policy_name => 'HMM_CARRIER_SCOPE_POLICY',
|
||||
function_schema => 'ADMIN',
|
||||
policy_function => 'HMM_CARRIER_VPD_FILTER',
|
||||
statement_types => 'SELECT',
|
||||
update_check => FALSE,
|
||||
enable => TRUE,
|
||||
policy_type => DBMS_RLS.CONTEXT_SENSITIVE
|
||||
);
|
||||
END;
|
||||
/
|
||||
|
||||
PROMPT === 5. Granting the non-exempt runtime read boundary ===
|
||||
GRANT SELECT ON hmm_carrier_assignments_v TO cb_ords;
|
||||
GRANT SELECT ON hmm_rds_carriers_v TO cb_ords;
|
||||
GRANT SELECT ON hmm_rds_carrier_perf_v TO cb_ords;
|
||||
GRANT SELECT ON hmm_rds_carrier_latest_v TO cb_ords;
|
||||
|
||||
CREATE OR REPLACE SYNONYM cb_ords.hmm_carrier_assignments_v
|
||||
FOR admin.hmm_carrier_assignments_v;
|
||||
CREATE OR REPLACE SYNONYM cb_ords.hmm_rds_carriers_v
|
||||
FOR admin.hmm_rds_carriers_v;
|
||||
CREATE OR REPLACE SYNONYM cb_ords.hmm_rds_carrier_perf_v
|
||||
FOR admin.hmm_rds_carrier_perf_v;
|
||||
CREATE OR REPLACE SYNONYM cb_ords.hmm_rds_carrier_latest_v
|
||||
FOR admin.hmm_rds_carrier_latest_v;
|
||||
|
||||
PROMPT === 6. Recording policy notes ===
|
||||
MERGE INTO hmm_access_vpd_filter_notes dst
|
||||
USING (
|
||||
SELECT 'ADMIN' function_owner,
|
||||
'HMM_CARRIER_VPD_FILTER' function_name,
|
||||
'Filters carrier assignments by the authenticated employee role and employee hierarchy.' description
|
||||
FROM dual
|
||||
) src
|
||||
ON (dst.function_owner = src.function_owner AND dst.function_name = src.function_name)
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
dst.description = src.description,
|
||||
dst.updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
function_owner, function_name, description, updated_at
|
||||
) VALUES (
|
||||
src.function_owner, src.function_name, src.description, SYSTIMESTAMP
|
||||
);
|
||||
|
||||
MERGE INTO hmm_access_vpd_policy_notes dst
|
||||
USING (
|
||||
SELECT 'ADMIN' object_owner,
|
||||
'HMM_CARRIER_ASSIGNMENTS_V' object_name,
|
||||
'HMM_CARRIER_SCOPE_POLICY' policy_name,
|
||||
'Restricts carrier assignments to self, direct reports, or explicit HR administrator access.' description
|
||||
FROM dual
|
||||
) src
|
||||
ON (
|
||||
dst.object_owner = src.object_owner
|
||||
AND dst.object_name = src.object_name
|
||||
AND dst.policy_name = src.policy_name
|
||||
)
|
||||
WHEN MATCHED THEN UPDATE SET
|
||||
dst.description = src.description,
|
||||
dst.updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN INSERT (
|
||||
object_owner, object_name, policy_name, description, updated_at
|
||||
) VALUES (
|
||||
src.object_owner, src.object_name, src.policy_name,
|
||||
src.description, SYSTIMESTAMP
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
|
||||
PROMPT === 7. Verification inventory ===
|
||||
SELECT object_name, policy_name, function, sel, enable, policy_type
|
||||
FROM all_policies
|
||||
WHERE object_owner = 'ADMIN'
|
||||
AND object_name = 'HMM_CARRIER_ASSIGNMENTS_V'
|
||||
AND policy_name = 'HMM_CARRIER_SCOPE_POLICY';
|
||||
|
||||
SELECT role.role_name,
|
||||
permission.target_name,
|
||||
rule.rule_column,
|
||||
rule.rule_type
|
||||
FROM hmm_access_permissions permission
|
||||
JOIN hmm_access_roles role ON role.role_id = permission.role_id
|
||||
JOIN hmm_access_permission_rules rule ON rule.perm_id = permission.perm_id
|
||||
WHERE permission.target_name = 'HMM_CARRIER_ASSIGNMENTS_V'
|
||||
ORDER BY role.role_name;
|
||||
|
||||
PROMPT === HMM carrier team VPD ready ===
|
||||
159
database/adb/85_hmm_hr_select_ai_no_annotation_profile.sql
Normal file
159
database/adb/85_hmm_hr_select_ai_no_annotation_profile.sql
Normal file
@@ -0,0 +1,159 @@
|
||||
-- Redmine #749
|
||||
-- Create an isolated HMM HR Select AI profile with annotations disabled.
|
||||
-- The source profile is never modified.
|
||||
|
||||
SET SERVEROUTPUT ON SIZE UNLIMITED
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE
|
||||
|
||||
DECLARE
|
||||
c_source_profile CONSTANT VARCHAR2(128) := 'HMM_HR_DATA_GPT54_PROFILE';
|
||||
c_target_profile CONSTANT VARCHAR2(128) := 'HMM_HR_DATA_GPT54_NOANN_PROFILE';
|
||||
|
||||
l_attributes CLOB;
|
||||
l_object_list CLOB;
|
||||
l_provider VARCHAR2(4000);
|
||||
l_credential_name VARCHAR2(4000);
|
||||
l_model VARCHAR2(4000);
|
||||
l_region VARCHAR2(4000);
|
||||
l_compartment_id VARCHAR2(4000);
|
||||
l_max_tokens NUMBER;
|
||||
l_temperature NUMBER;
|
||||
l_profile_count PLS_INTEGER;
|
||||
l_difference_count PLS_INTEGER;
|
||||
l_annotations VARCHAR2(30);
|
||||
|
||||
FUNCTION attribute_clob(p_name IN VARCHAR2) RETURN CLOB IS
|
||||
l_value CLOB;
|
||||
BEGIN
|
||||
SELECT attribute_value
|
||||
INTO l_value
|
||||
FROM user_cloud_ai_profile_attributes
|
||||
WHERE profile_name = c_source_profile
|
||||
AND attribute_name = p_name;
|
||||
RETURN l_value;
|
||||
END attribute_clob;
|
||||
|
||||
FUNCTION attribute_text(p_name IN VARCHAR2) RETURN VARCHAR2 IS
|
||||
BEGIN
|
||||
RETURN DBMS_LOB.SUBSTR(attribute_clob(p_name), 4000, 1);
|
||||
END attribute_text;
|
||||
BEGIN
|
||||
SELECT COUNT(*)
|
||||
INTO l_profile_count
|
||||
FROM user_cloud_ai_profiles
|
||||
WHERE profile_name = c_source_profile
|
||||
AND status = 'ENABLED';
|
||||
|
||||
IF l_profile_count <> 1 THEN
|
||||
RAISE_APPLICATION_ERROR(-20080, 'Enabled source Select AI profile was not found.');
|
||||
END IF;
|
||||
|
||||
l_provider := attribute_text('provider');
|
||||
l_credential_name := attribute_text('credential_name');
|
||||
l_model := attribute_text('model');
|
||||
l_region := attribute_text('region');
|
||||
l_compartment_id := attribute_text('oci_compartment_id');
|
||||
l_object_list := attribute_clob('object_list');
|
||||
l_max_tokens := TO_NUMBER(
|
||||
attribute_text('max_tokens'),
|
||||
'9999999999',
|
||||
'NLS_NUMERIC_CHARACTERS=''.,'''
|
||||
);
|
||||
l_temperature := TO_NUMBER(
|
||||
attribute_text('temperature'),
|
||||
'9999999990D999999999',
|
||||
'NLS_NUMERIC_CHARACTERS=''.,'''
|
||||
);
|
||||
|
||||
SELECT COUNT(*)
|
||||
INTO l_profile_count
|
||||
FROM user_cloud_ai_profiles
|
||||
WHERE profile_name = c_target_profile;
|
||||
|
||||
IF l_profile_count = 0 THEN
|
||||
SELECT JSON_OBJECT(
|
||||
'provider' VALUE l_provider,
|
||||
'credential_name' VALUE l_credential_name,
|
||||
'model' VALUE l_model,
|
||||
'region' VALUE l_region,
|
||||
'oci_compartment_id' VALUE l_compartment_id,
|
||||
'object_list' VALUE l_object_list FORMAT JSON,
|
||||
'max_tokens' VALUE l_max_tokens,
|
||||
'temperature' VALUE l_temperature,
|
||||
'annotations' VALUE 'false' FORMAT JSON
|
||||
RETURNING CLOB
|
||||
)
|
||||
INTO l_attributes
|
||||
FROM dual;
|
||||
|
||||
DBMS_CLOUD_AI.CREATE_PROFILE(
|
||||
profile_name => c_target_profile,
|
||||
attributes => l_attributes,
|
||||
status => 'enabled',
|
||||
description => 'HMM HR GPT-5.4 mini comparison profile with annotations disabled'
|
||||
);
|
||||
DBMS_OUTPUT.PUT_LINE('PROFILE_CREATED|' || c_target_profile);
|
||||
ELSE
|
||||
DBMS_OUTPUT.PUT_LINE('PROFILE_EXISTS|' || c_target_profile);
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*)
|
||||
INTO l_difference_count
|
||||
FROM (
|
||||
SELECT attribute_name, attribute_value
|
||||
FROM user_cloud_ai_profile_attributes
|
||||
WHERE profile_name = c_source_profile
|
||||
AND attribute_name <> 'annotations'
|
||||
) source_attributes
|
||||
FULL OUTER JOIN (
|
||||
SELECT attribute_name, attribute_value
|
||||
FROM user_cloud_ai_profile_attributes
|
||||
WHERE profile_name = c_target_profile
|
||||
AND attribute_name <> 'annotations'
|
||||
) target_attributes
|
||||
ON target_attributes.attribute_name = source_attributes.attribute_name
|
||||
WHERE source_attributes.attribute_name IS NULL
|
||||
OR target_attributes.attribute_name IS NULL
|
||||
OR DBMS_LOB.COMPARE(
|
||||
source_attributes.attribute_value,
|
||||
target_attributes.attribute_value
|
||||
) <> 0;
|
||||
|
||||
SELECT LOWER(TRIM(DBMS_LOB.SUBSTR(attribute_value, 30, 1)))
|
||||
INTO l_annotations
|
||||
FROM user_cloud_ai_profile_attributes
|
||||
WHERE profile_name = c_target_profile
|
||||
AND attribute_name = 'annotations';
|
||||
|
||||
IF l_difference_count <> 0 OR l_annotations <> 'false' THEN
|
||||
RAISE_APPLICATION_ERROR(
|
||||
-20081,
|
||||
'Comparison profile differs from source beyond annotations=false.'
|
||||
);
|
||||
END IF;
|
||||
|
||||
DBMS_OUTPUT.PUT_LINE(
|
||||
'PROFILE_VALIDATED|source=' || c_source_profile
|
||||
|| '|target=' || c_target_profile
|
||||
|| '|annotations=false|other_attribute_differences=0'
|
||||
);
|
||||
END;
|
||||
/
|
||||
|
||||
SELECT profile_name, status, description
|
||||
FROM user_cloud_ai_profiles
|
||||
WHERE profile_name IN (
|
||||
'HMM_HR_DATA_GPT54_PROFILE',
|
||||
'HMM_HR_DATA_GPT54_NOANN_PROFILE'
|
||||
)
|
||||
ORDER BY profile_name;
|
||||
|
||||
SELECT profile_name, attribute_name, attribute_value
|
||||
FROM user_cloud_ai_profile_attributes
|
||||
WHERE profile_name IN (
|
||||
'HMM_HR_DATA_GPT54_PROFILE',
|
||||
'HMM_HR_DATA_GPT54_NOANN_PROFILE'
|
||||
)
|
||||
ORDER BY profile_name, attribute_name;
|
||||
|
||||
EXIT SUCCESS
|
||||
103
database/adb/86_hmm_select_ai_annotation_benchmark.sql
Normal file
103
database/adb/86_hmm_select_ai_annotation_benchmark.sql
Normal file
@@ -0,0 +1,103 @@
|
||||
-- Redmine #749
|
||||
-- Compare Select AI prompt and SQL generation with annotations enabled/disabled.
|
||||
-- The Korean prompt is reconstructed from UTF-8 Base64 inside Oracle.
|
||||
|
||||
SET SERVEROUTPUT ON SIZE UNLIMITED
|
||||
SET FEEDBACK OFF
|
||||
SET VERIFY OFF
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE
|
||||
|
||||
DECLARE
|
||||
c_annotation_profile CONSTANT VARCHAR2(128) := 'HMM_HR_DATA_GPT54_PROFILE';
|
||||
c_no_annotation_profile CONSTANT VARCHAR2(128) := 'HMM_HR_DATA_GPT54_NOANN_PROFILE';
|
||||
c_prompt_base64 CONSTANT VARCHAR2(4000) :=
|
||||
'7J2067KIIOuLrCDtjIDsm5Drs4Qg7Zy06rCAIOyCrOyaqSDtmITtmansnYQg67O07Jes7KSY';
|
||||
|
||||
l_prompt VARCHAR2(4000) :=
|
||||
UTL_I18N.RAW_TO_CHAR(
|
||||
UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(c_prompt_base64)),
|
||||
'AL32UTF8'
|
||||
);
|
||||
|
||||
PROCEDURE run_one(
|
||||
p_run_no IN PLS_INTEGER,
|
||||
p_action IN VARCHAR2,
|
||||
p_profile_name IN VARCHAR2
|
||||
) IS
|
||||
l_started PLS_INTEGER;
|
||||
l_elapsed_ms PLS_INTEGER;
|
||||
l_result CLOB;
|
||||
l_result_head VARCHAR2(32767);
|
||||
l_result_hash VARCHAR2(128);
|
||||
l_valid_sql VARCHAR2(1) := '-';
|
||||
BEGIN
|
||||
l_started := DBMS_UTILITY.GET_TIME;
|
||||
l_result := DBMS_CLOUD_AI.GENERATE(
|
||||
l_prompt,
|
||||
p_profile_name,
|
||||
p_action
|
||||
);
|
||||
l_elapsed_ms := (DBMS_UTILITY.GET_TIME - l_started) * 10;
|
||||
l_result_head := DBMS_LOB.SUBSTR(l_result, 32767, 1);
|
||||
SELECT RAWTOHEX(STANDARD_HASH(l_result_head, 'SHA256'))
|
||||
INTO l_result_hash
|
||||
FROM dual;
|
||||
|
||||
IF p_action = 'showsql' THEN
|
||||
IF REGEXP_LIKE(LTRIM(l_result_head), '^(SELECT|WITH)[[:space:]]', 'i') THEN
|
||||
l_valid_sql := 'Y';
|
||||
ELSE
|
||||
l_valid_sql := 'N';
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
DBMS_OUTPUT.PUT_LINE(
|
||||
'BENCHMARK|run=' || p_run_no
|
||||
|| '|action=' || p_action
|
||||
|| '|profile=' || p_profile_name
|
||||
|| '|elapsed_ms=' || l_elapsed_ms
|
||||
|| '|result_chars=' || DBMS_LOB.GETLENGTH(l_result)
|
||||
|| '|valid_sql=' || l_valid_sql
|
||||
|| '|result_sha256=' || l_result_hash
|
||||
);
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
l_elapsed_ms := (DBMS_UTILITY.GET_TIME - l_started) * 10;
|
||||
DBMS_OUTPUT.PUT_LINE(
|
||||
'BENCHMARK_ERROR|run=' || p_run_no
|
||||
|| '|action=' || p_action
|
||||
|| '|profile=' || p_profile_name
|
||||
|| '|elapsed_ms=' || l_elapsed_ms
|
||||
|| '|error=' || REPLACE(SUBSTR(SQLERRM, 1, 500), '|', '/')
|
||||
);
|
||||
END run_one;
|
||||
|
||||
PROCEDURE run_pair(p_run_no IN PLS_INTEGER, p_action IN VARCHAR2) IS
|
||||
BEGIN
|
||||
IF MOD(p_run_no, 2) = 1 THEN
|
||||
run_one(p_run_no, p_action, c_annotation_profile);
|
||||
run_one(p_run_no, p_action, c_no_annotation_profile);
|
||||
ELSE
|
||||
run_one(p_run_no, p_action, c_no_annotation_profile);
|
||||
run_one(p_run_no, p_action, c_annotation_profile);
|
||||
END IF;
|
||||
END run_pair;
|
||||
BEGIN
|
||||
DBMS_OUTPUT.PUT_LINE(
|
||||
'BENCHMARK_START|prompt_utf8_bytes=' ||
|
||||
UTL_RAW.LENGTH(UTL_I18N.STRING_TO_RAW(l_prompt, 'AL32UTF8'))
|
||||
);
|
||||
|
||||
FOR run_no IN 1 .. 3 LOOP
|
||||
run_pair(run_no, 'showprompt');
|
||||
END LOOP;
|
||||
|
||||
FOR run_no IN 1 .. 3 LOOP
|
||||
run_pair(run_no, 'showsql');
|
||||
END LOOP;
|
||||
|
||||
DBMS_OUTPUT.PUT_LINE('BENCHMARK_END');
|
||||
END;
|
||||
/
|
||||
|
||||
EXIT SUCCESS
|
||||
@@ -42,6 +42,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-oauth2-jose</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.oracle.database.jdbc</groupId>
|
||||
<artifactId>ojdbc11</artifactId>
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.cloudhandson.ddsbackoffice;
|
||||
|
||||
import com.cloudhandson.ddsbackoffice.config.DdsProperties;
|
||||
import com.cloudhandson.ddsbackoffice.config.DdsMcpIamProperties;
|
||||
import com.cloudhandson.ddsbackoffice.config.DdsMcpOidcProperties;
|
||||
import com.cloudhandson.vpdbackoffice.VpdBackofficeApplication;
|
||||
import com.cloudhandson.vpdbackoffice.web.DashboardController;
|
||||
import com.cloudhandson.vpdbackoffice.web.LoginController;
|
||||
@@ -15,7 +16,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableConfigurationProperties({DdsProperties.class, DdsMcpIamProperties.class})
|
||||
@EnableConfigurationProperties({DdsProperties.class, DdsMcpIamProperties.class, DdsMcpOidcProperties.class})
|
||||
@MapperScan("com.cloudhandson.vpdbackoffice.mapper")
|
||||
@ComponentScan(
|
||||
basePackages = {"com.cloudhandson.ddsbackoffice", "com.cloudhandson.vpdbackoffice"},
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.cloudhandson.ddsbackoffice.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtValidators;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "dds.mcp.oidc", name = "enabled", havingValue = "true")
|
||||
public class DdsMcpOidcConfiguration {
|
||||
|
||||
@Bean
|
||||
JwtDecoder ddsMcpJwtDecoder(DdsMcpOidcProperties properties) {
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(properties.issuerUri()).build();
|
||||
OAuth2TokenValidator<Jwt> audienceValidator = jwt -> jwt.getAudience().contains(properties.audience())
|
||||
? OAuth2TokenValidatorResult.success()
|
||||
: OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token", "Invalid audience", null));
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
|
||||
JwtValidators.createDefaultWithIssuer(properties.issuerUri()), audienceValidator));
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.cloudhandson.ddsbackoffice.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.ConstructorBinding;
|
||||
|
||||
/** OIDC resource-server settings for externally authenticated MCP callers. */
|
||||
@ConfigurationProperties(prefix = "dds.mcp.oidc")
|
||||
public record DdsMcpOidcProperties(boolean enabled, String issuerUri, String audience) {
|
||||
|
||||
@ConstructorBinding
|
||||
public DdsMcpOidcProperties {
|
||||
issuerUri = trim(issuerUri);
|
||||
audience = trim(audience);
|
||||
if (enabled && (issuerUri.isBlank() || audience.isBlank())) {
|
||||
throw new IllegalArgumentException("DDS MCP OIDC issuer-uri와 audience를 설정해야 합니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String trim(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
@@ -24,13 +24,13 @@ public class SecurityConfig {
|
||||
}
|
||||
|
||||
return http
|
||||
.csrf(csrf -> csrf.ignoringRequestMatchers("/dds/mcp/messages"))
|
||||
.csrf(csrf -> csrf.ignoringRequestMatchers("/dds/mcp/messages", "/mcp/dds/messages"))
|
||||
.headers(headers -> headers.httpStrictTransportSecurity(hsts -> hsts
|
||||
.includeSubDomains(true)
|
||||
.maxAgeInSeconds(31_536_000)))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/css/**", "/js/**", "/health", "/login",
|
||||
"/dds/mcp/sse", "/dds/mcp/messages").permitAll()
|
||||
"/dds/mcp/sse", "/dds/mcp/messages", "/mcp/dds/sse", "/mcp/dds/messages").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.httpBasic(basic -> {
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.cloudhandson.ddsbackoffice.service;
|
||||
|
||||
import com.cloudhandson.vpdbackoffice.service.DdsAuthorizationSynchronizer;
|
||||
import com.cloudhandson.vpdbackoffice.service.ExternalAuthorizationSynchronizer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
@@ -8,7 +8,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
/** Republishes all local DDS MCP identities in the same request as an authorization change. */
|
||||
@Component
|
||||
public class DdsMcpAuthorizationChangeListener implements DdsAuthorizationSynchronizer {
|
||||
public class DdsMcpAuthorizationChangeListener implements ExternalAuthorizationSynchronizer {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DdsMcpAuthorizationChangeListener.class);
|
||||
private final DdsMcpEndUserPublisher publisher;
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.cloudhandson.vpdbackoffice.service.BearerTokenService;
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Revalidates the MCP request bearer before every tool invocation. */
|
||||
@@ -20,22 +21,32 @@ public class DdsMcpBearerAuthenticator {
|
||||
private final BearerTokenService bearerTokenService;
|
||||
private final UserMapper userMapper;
|
||||
private final DdsMcpEndUserResolver endUserResolver;
|
||||
private final ObjectProvider<DdsMcpOidcAuthenticator> oidcAuthenticator;
|
||||
private final Clock clock;
|
||||
|
||||
public DdsMcpBearerAuthenticator(
|
||||
BearerTokenService bearerTokenService,
|
||||
UserMapper userMapper,
|
||||
DdsMcpEndUserResolver endUserResolver,
|
||||
ObjectProvider<DdsMcpOidcAuthenticator> oidcAuthenticator,
|
||||
Clock clock
|
||||
) {
|
||||
this.bearerTokenService = bearerTokenService;
|
||||
this.userMapper = userMapper;
|
||||
this.endUserResolver = endUserResolver;
|
||||
this.oidcAuthenticator = oidcAuthenticator;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public DdsMcpAuthenticatedUser authenticate(String authorization) {
|
||||
String plainToken = bearerValue(authorization);
|
||||
if (plainToken.chars().filter(character -> character == '.').count() == 2) {
|
||||
DdsMcpOidcAuthenticator oidc = oidcAuthenticator.getIfAvailable();
|
||||
if (oidc == null) {
|
||||
throw denied();
|
||||
}
|
||||
return oidc.authenticate(plainToken);
|
||||
}
|
||||
BearerTokenRecord token = bearerTokenService.findByPlainToken(plainToken);
|
||||
LocalDateTime now = LocalDateTime.now(clock.withZone(ZoneId.systemDefault()));
|
||||
if (token == null || !token.active(now) || !bearerTokenService.matches(token, plainToken)) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.cloudhandson.ddsbackoffice.service;
|
||||
|
||||
import com.cloudhandson.vpdbackoffice.service.AppException;
|
||||
import java.util.List;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Maps a verified OIDC issuer and subject to one active HMM application user. */
|
||||
@Service
|
||||
public class DdsMcpExternalIdentityResolver {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public DdsMcpExternalIdentityResolver(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public long resolveApplicationUserId(String issuer, String subject) {
|
||||
if (!safe(issuer) || !safe(subject)) {
|
||||
throw denied();
|
||||
}
|
||||
try {
|
||||
List<Long> userIds = jdbcTemplate.query("""
|
||||
SELECT b.application_user_id
|
||||
FROM cb_external_identity_binding b
|
||||
JOIN cb_app_user u ON u.user_id = b.application_user_id
|
||||
WHERE b.issuer = ?
|
||||
AND b.subject = ?
|
||||
AND b.active = 'Y'
|
||||
AND u.active = 'Y'
|
||||
""", (row, ignored) -> row.getLong("application_user_id"), issuer, subject);
|
||||
if (userIds.size() != 1) {
|
||||
throw denied();
|
||||
}
|
||||
return userIds.getFirst();
|
||||
} catch (AppException exception) {
|
||||
throw exception;
|
||||
} catch (DataAccessException exception) {
|
||||
throw new AppException("DDS_CONTEXT_UNAVAILABLE: 외부 ID 매핑을 확인할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean safe(String value) {
|
||||
return value != null && !value.isBlank() && value.length() <= 512;
|
||||
}
|
||||
|
||||
private AppException denied() {
|
||||
return new AppException("AUTHORIZATION_DENIED: 외부 OIDC 사용자를 DDS에 매핑할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.cloudhandson.ddsbackoffice.service;
|
||||
|
||||
import com.cloudhandson.ddsbackoffice.domain.DdsMcpAuthenticatedUser;
|
||||
import com.cloudhandson.vpdbackoffice.domain.user.AppUser;
|
||||
import com.cloudhandson.vpdbackoffice.mapper.UserMapper;
|
||||
import com.cloudhandson.vpdbackoffice.service.AppException;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Validates a signed OIDC JWT before looking up the DDS identity bridge. */
|
||||
@Service
|
||||
@ConditionalOnProperty(prefix = "dds.mcp.oidc", name = "enabled", havingValue = "true")
|
||||
public class DdsMcpOidcAuthenticator {
|
||||
|
||||
private final JwtDecoder jwtDecoder;
|
||||
private final DdsMcpExternalIdentityResolver externalIdentityResolver;
|
||||
private final UserMapper userMapper;
|
||||
private final DdsMcpEndUserResolver endUserResolver;
|
||||
|
||||
public DdsMcpOidcAuthenticator(
|
||||
JwtDecoder jwtDecoder,
|
||||
DdsMcpExternalIdentityResolver externalIdentityResolver,
|
||||
UserMapper userMapper,
|
||||
DdsMcpEndUserResolver endUserResolver
|
||||
) {
|
||||
this.jwtDecoder = jwtDecoder;
|
||||
this.externalIdentityResolver = externalIdentityResolver;
|
||||
this.userMapper = userMapper;
|
||||
this.endUserResolver = endUserResolver;
|
||||
}
|
||||
|
||||
public DdsMcpAuthenticatedUser authenticate(String token) {
|
||||
try {
|
||||
Jwt jwt = jwtDecoder.decode(token);
|
||||
long userId = externalIdentityResolver.resolveApplicationUserId(
|
||||
jwt.getIssuer() == null ? null : jwt.getIssuer().toString(), jwt.getSubject());
|
||||
AppUser user = userMapper.findById(userId);
|
||||
if (user == null || !user.active()) {
|
||||
throw denied();
|
||||
}
|
||||
return new DdsMcpAuthenticatedUser(user.userId(), user.username(), endUserResolver.resolve(user.userId()));
|
||||
} catch (AppException exception) {
|
||||
throw exception;
|
||||
} catch (JwtException | IllegalArgumentException exception) {
|
||||
throw denied();
|
||||
}
|
||||
}
|
||||
|
||||
private AppException denied() {
|
||||
return new AppException("AUTHORIZATION_DENIED: MCP OIDC 토큰을 확인할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,8 @@ public class DdsMcpVectorSearchService {
|
||||
log.info("DDS vector query completed with {} rows", rows.size());
|
||||
return new DdsMcpVectorSearchResult(vector.query(), vector.embeddingMode(), rows.size(), List.copyOf(rows));
|
||||
} catch (java.sql.SQLException exception) {
|
||||
log.warn("DDS vector query failed: sqlState={}, errorCode={}",
|
||||
exception.getSQLState(), exception.getErrorCode());
|
||||
throw new AppException("DDS_QUERY_FAILED: DDS 보호 객체를 조회할 수 없습니다.");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.cloudhandson.ddsbackoffice.service.DdsMcpSseService;
|
||||
import com.cloudhandson.vpdbackoffice.service.AppException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -38,8 +39,11 @@ public class DdsMcpSseController {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping(path = "/dds/mcp/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter sse(@RequestHeader(name = "Authorization", required = false) String authorization) throws IOException {
|
||||
@GetMapping(path = {"/dds/mcp/sse", "/mcp/dds/sse"}, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter sse(
|
||||
@RequestHeader(name = "Authorization", required = false) String authorization,
|
||||
HttpServletRequest request
|
||||
) throws IOException {
|
||||
DdsMcpAuthenticatedUser user = bearerAuthenticator.authenticate(authorization);
|
||||
String sessionId = UUID.randomUUID().toString();
|
||||
SseEmitter emitter = new SseEmitter(SSE_TIMEOUT_MILLIS);
|
||||
@@ -47,11 +51,14 @@ public class DdsMcpSseController {
|
||||
emitter.onCompletion(() -> sessions.remove(sessionId));
|
||||
emitter.onTimeout(() -> sessions.remove(sessionId));
|
||||
emitter.onError(error -> sessions.remove(sessionId));
|
||||
emitter.send(SseEmitter.event().name("endpoint").data("/dds/mcp/messages?sessionId=" + sessionId));
|
||||
String messagesPath = request.getRequestURI().startsWith("/mcp/dds/")
|
||||
? "/mcp/dds/messages"
|
||||
: "/dds/mcp/messages";
|
||||
emitter.send(SseEmitter.event().name("endpoint").data(messagesPath + "?sessionId=" + sessionId));
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@PostMapping(path = "/dds/mcp/messages", consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@PostMapping(path = {"/dds/mcp/messages", "/mcp/dds/messages"}, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> message(
|
||||
@RequestHeader(name = "Authorization", required = false) String authorization,
|
||||
@RequestParam(required = false) String sessionId,
|
||||
|
||||
@@ -58,6 +58,12 @@ backoffice:
|
||||
dds:
|
||||
mcp:
|
||||
permission-sync-enabled: true
|
||||
oidc:
|
||||
# Disabled unless an external OIDC issuer is explicitly configured.
|
||||
# The production issuer must use HTTPS; the isolated AD VM uses a temporary HTTP value only for PoC.
|
||||
enabled: ${DDS_MCP_OIDC_ENABLED:false}
|
||||
issuer-uri: ${DDS_MCP_OIDC_ISSUER_URI:}
|
||||
audience: ${DDS_MCP_OIDC_AUDIENCE:dds-mcp}
|
||||
iam:
|
||||
domain-url: ${DDS_OCI_IAM_DOMAIN_URL:}
|
||||
token-uri: ${DDS_OCI_IAM_TOKEN_URI:}
|
||||
|
||||
@@ -3,8 +3,8 @@ package com.cloudhandson.ddsbackoffice.service;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.cloudhandson.vpdbackoffice.service.DdsAuthorizationChangeNotifier;
|
||||
import com.cloudhandson.vpdbackoffice.service.DdsAuthorizationSynchronizer;
|
||||
import com.cloudhandson.vpdbackoffice.service.ExternalAuthorizationChangeNotifier;
|
||||
import com.cloudhandson.vpdbackoffice.service.ExternalAuthorizationSynchronizer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
|
||||
@@ -16,9 +16,9 @@ class DdsMcpAuthorizationChangeListenerTest {
|
||||
when(publisher.publish()).thenReturn(new com.cloudhandson.ddsbackoffice.domain.DdsMcpEndUserPublishResult(3, 0, 0));
|
||||
DdsMcpAuthorizationChangeListener listener = new DdsMcpAuthorizationChangeListener(publisher);
|
||||
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
|
||||
factory.registerSingleton("ddsSynchronizer", (DdsAuthorizationSynchronizer) listener);
|
||||
factory.registerSingleton("ddsSynchronizer", (ExternalAuthorizationSynchronizer) listener);
|
||||
|
||||
new DdsAuthorizationChangeNotifier(factory.getBeanProvider(DdsAuthorizationSynchronizer.class))
|
||||
new ExternalAuthorizationChangeNotifier(factory.getBeanProvider(ExternalAuthorizationSynchronizer.class))
|
||||
.changed("PERMISSION_SAVED");
|
||||
|
||||
verify(publisher).publish();
|
||||
|
||||
@@ -11,7 +11,7 @@ BACKOFFICE_PRODUCT_DATA_LABEL='HMM HR 데이터'
|
||||
|
||||
BACKOFFICE_MCP_PUBLIC_URL='https://hmm-backoffice.cloud-handson.com/mcp'
|
||||
BACKOFFICE_MCP_SERVER_NAME='hmm-hr-backoffice'
|
||||
BACKOFFICE_MCP_TOOLS='[{"name":"resolve_hr_term","label":"HMM HR 용어 표준화","description":"휴가·근태 표현을 HMM 표준 용어와 코드로 변환합니다. 모호한 표현은 데이터 조회 전에 이 도구를 사용합니다.","argumentName":"term","argumentDescription":"확인할 휴가·근태 용어, 동의어 또는 코드입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_TERM_RESOLVER","targetParameterName":"P_TERM"},{"name":"search_hr_data","label":"HMM HR 데이터 조회","description":"조직, 직원, 휴가 잔여·신청, 근태 데이터를 읽기 전용 Select AI로 조회합니다.","argumentName":"query","argumentDescription":"조직, 직원, 휴가 또는 근태에 대한 완전한 자연어 질문입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_NORMALIZED_DATA_SEARCH","targetParameterName":"P_QUERY"},{"name":"search_hr_policy","label":"HMM HR 규정 검색","description":"HR 규정 PDF의 문서 메타데이터, Abstract, 관련 청크를 계층형 벡터 검색으로 조회합니다.","argumentName":"query","argumentDescription":"HR 규정에 대한 완전한 자연어 질문입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_POLICY_SEARCH","targetParameterName":"P_QUERY"}]'
|
||||
BACKOFFICE_MCP_TOOLS='[{"name":"resolve_hr_term","label":"HMM HR 용어 표준화","description":"휴가·근태 표현을 HMM 표준 용어와 코드로 변환합니다. 모호한 표현은 데이터 조회 전에 이 도구를 사용합니다.","argumentName":"term","argumentDescription":"확인할 휴가·근태 용어, 동의어 또는 코드입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_TERM_RESOLVER","targetParameterName":"P_TERM"},{"name":"search_hr_data","label":"HMM HR 데이터 조회","description":"조직, 직원, 휴가 잔여·신청, 근태 데이터를 읽기 전용 Select AI로 조회합니다.","argumentName":"query","argumentDescription":"조직, 직원, 휴가 또는 근태에 대한 완전한 자연어 질문입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_NORMALIZED_DATA_SEARCH","targetParameterName":"P_QUERY"},{"name":"search_hr_policy","label":"HMM HR 규정 검색","description":"HR 규정 PDF의 문서 메타데이터, Abstract, 관련 청크를 계층형 벡터 검색으로 조회합니다.","argumentName":"query","argumentDescription":"HR 규정에 대한 완전한 자연어 질문입니다.","executionType":"AGENT_TOOL","targetName":"HMM_HR_POLICY_SEARCH","targetParameterName":"P_QUERY"},{"name":"search_carrier_performance","label":"HMM 선사 실적 Federation 조회","description":"팀원별 담당 선사의 최신 매출, 매출총이익, 정시 운항률과 위험 등급을 Select AI Federation으로 조회합니다.","argumentName":"query","argumentDescription":"선사 실적에 대한 완전한 자연어 질문입니다.","executionType":"AGENT_TOOL","targetName":"HMM_CARRIER_FEDERATION_SEARCH","targetParameterName":"P_QUERY"},{"name":"render_hmm_carrier_report","label":"HMM 선사 실적 HTML 리포트","description":"이미 권한이 적용된 조회 결과를 HMM HTML 리포트로 표현합니다. 데이터를 조회하거나 값을 변경하지 않는 후속 처리 전용 Tool입니다.","argumentName":"reportJson","argumentDescription":"앞 단계의 구조화된 조회 결과와 리포트 메타데이터를 담은 JSON입니다.","executionType":"AGENT_TOOL","targetName":"HMM_CARRIER_REPORT_RENDERER","targetParameterName":"P_REPORT_JSON"}]'
|
||||
|
||||
BACKOFFICE_MASKING_POLICIES='[{"objectName":"HMM_HR_EMPLOYEES","policyName":"HMM_EMPLOYEE_PII_REDACT"},{"objectName":"HMM_LEAVE_BALANCES","policyName":"HMM_LEAVE_BALANCE_REDACT"},{"objectName":"HMM_LEAVE_REQUESTS","policyName":"HMM_LEAVE_REQUEST_REDACT"},{"objectName":"HMM_ATTENDANCE_DAILY","policyName":"HMM_ATTENDANCE_REDACT"}]'
|
||||
|
||||
|
||||
43
docs/DOCUMENTATION-STANDARDS.md
Normal file
43
docs/DOCUMENTATION-STANDARDS.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# 문서 구조 표준
|
||||
|
||||
## 목적
|
||||
|
||||
문서를 처음 보는 사람이 전체 구조를 빠르게 이해하고, 필요한 순간에만 적용 방법이나 장애 해결 세부사항으로 내려갈 수 있게 한다.
|
||||
|
||||
## 기본 문서 지도
|
||||
|
||||
```text
|
||||
README.md 무엇을, 왜 하는가 / 현재 상태 / 큰그림
|
||||
├── architecture.md 어떻게 구성되며 누가 무엇을 신뢰하는가
|
||||
├── cookbook.md 어떻게 적용·검증·되돌리는가
|
||||
└── troubleshooting.md 무엇이 실패했고 어떻게 진단·해결하는가
|
||||
```
|
||||
|
||||
## README 필수 항목
|
||||
|
||||
- 목적·범위·제외 범위
|
||||
- 현재 상태와 검증된 사실
|
||||
- 구성요소 5~7개 이하의 개요도
|
||||
- 핵심 결정 3~5개
|
||||
- 상세 문서 링크와 독자가 어떤 경우에 읽어야 하는지
|
||||
|
||||
## 상세 문서 규칙
|
||||
|
||||
| 문서 | 포함할 내용 | 포함하지 않을 내용 |
|
||||
|---|---|---|
|
||||
| `architecture.md` | 신뢰 경계, 구성요소 책임, 상세 흐름, 데이터 모델, 설계 근거 | 긴 설치 명령과 오류 이력 |
|
||||
| `cookbook.md` | 준비물, 단계, 입력값 형식, 성공 판정, rollback, 관련 troubleshooting 링크 | 설계 배경의 반복 |
|
||||
| `troubleshooting.md` | 증상, 원인, 확인 명령, 해결, 재발 방지 | secret 값, 원인 없는 임시 우회 |
|
||||
|
||||
## 그림 규칙
|
||||
|
||||
- README 개요도는 경계와 흐름만 보여 주고 화살표는 가능한 한 10개 이하로 유지한다.
|
||||
- 포트, claim, redirect URI, DB role처럼 세부값이 필요한 내용은 상세도 또는 표로 분리한다.
|
||||
- 그림 아래에 “이 그림에서 기억할 점”을 적는다.
|
||||
- Mermaid를 쓸 때는 노드 이름을 짧게 하고, 긴 설명은 표 또는 본문으로 옮긴다.
|
||||
|
||||
## 보안과 검증
|
||||
|
||||
- 비밀번호·secret·token·cookie는 예시에도 넣지 않는다.
|
||||
- 각 cookbook 단계는 성공 판정과 다음 조치를 포함한다.
|
||||
- 문서를 마칠 때는 링크 유효성, Mermaid 문법, 용어 일관성, secret 노출 여부를 점검한다.
|
||||
@@ -61,3 +61,11 @@ docs/
|
||||
`Draft`(작성) → `Approved`(QA/Reviewer 통과 후) → `Superseded`(대체 시 상단 표기, 삭제 금지).
|
||||
구현이 설계서와 달라지면 **코드가 아니라 설계서를 먼저 고치고** 다시 구현한다.
|
||||
```
|
||||
# 문서 안내
|
||||
|
||||
## HMM 운영 문서
|
||||
|
||||
- [HMM MCP·VPD 운영 가이드](runbooks/hmm-mcp-vpd-operations.md)
|
||||
- [HMM MCP 토큰 설정](runbooks/hmm-mcp-token-configuration.md)
|
||||
|
||||
공통 MCP·VPD·Data Redaction·DDS 절차는 `main`의 공통 운영 문서를 기준으로 한다.
|
||||
|
||||
@@ -1,123 +1,55 @@
|
||||
# #740 HMM MCP VPD 실행 경계 복구
|
||||
# #740 HMM MCP VPD 실행 경계
|
||||
|
||||
## 배경
|
||||
## 목적
|
||||
|
||||
HMM MCP의 `search_hr_data`는 현재 `ADMIN` JDBC 세션에서
|
||||
`DBMS_CLOUD_AI_AGENT.RUN_TOOL`을 실행한다. 토큰으로
|
||||
`HMM_ACCESS_CTX`를 설정해도 `ADMIN`에는 `EXEMPT ACCESS POLICY`가 있으므로
|
||||
`ADMIN.HMM_LEAVE_BALANCES`와 `ADMIN.HMM_LEAVE_REQUESTS`의 VPD 정책이
|
||||
실제 조회에 적용되지 않는다.
|
||||
HMM MCP의 인증 사용자를 Oracle DB 세션 사용자 문맥으로 연결하고, HR 및 선사 배정 데이터를
|
||||
Oracle VPD로 제한한다. 팀원은 본인 행, 팀장은 본인과 직속 팀원 행을 조회한다.
|
||||
|
||||
컨텍스트 값이 올바른 것과 VPD가 적용되는 것은 별개의 조건이다. 보호 테이블을
|
||||
읽는 최종 SQL은 반드시 `EXEMPT ACCESS POLICY`가 없는 계정의 동일 DB 세션에서
|
||||
컨텍스트 설정과 함께 실행해야 한다.
|
||||
## 범위와 결정사항
|
||||
|
||||
## 목표
|
||||
- 포털의 사용자 preset은 각각 다른 Bearer token 환경변수를 사용한다.
|
||||
- 백오피스는 token hash로 직원을 식별하고 실제 SELECT와 같은 `CB_ORDS` 연결에
|
||||
`SET_VPD_CONTEXT`를 호출한다.
|
||||
- `ADMIN`은 `EXEMPT ACCESS POLICY`가 있으므로 Select AI `SHOWSQL` 생성만 담당한다.
|
||||
- `HMM_CARRIER_ASSIGNMENTS_V.EMPLOYEE_ID`에 `SELF`, `MANAGED_TEAM`, `ALL` 규칙을 적용한다.
|
||||
- 기존 MCP 이름 `search_carrier_performance`, 자연어 Select AI, 선사 `CARRIER_CODE` 조인과 HTML
|
||||
renderer는 유지한다. 고정 SQL이나 대체 조회 패키지를 만들지 않는다.
|
||||
- 연속 호출에서도 renderer 입력이 달라지지 않도록 Select AI 질의 계약이 출력 컬럼의 ASCII
|
||||
uppercase underscore 별칭을 고정한다.
|
||||
|
||||
- `ADMIN`은 Select AI `SHOWSQL` 생성만 담당한다.
|
||||
- 비면제 런타임 스키마 `CB_ORDS`가 생성 SQL을 읽기 전용으로 실행한다.
|
||||
- 실행 직전 같은 `CB_ORDS` 세션에서
|
||||
`CB_ORDS_HANDLER_PKG.SET_VPD_CONTEXT`를 호출한다.
|
||||
- 실행 종료 시 성공·실패와 관계없이 `CLEAR_VPD_CONTEXT`를 호출하고 롤백한다.
|
||||
- 런타임 계정이 `ADMIN`이거나 `EXEMPT ACCESS POLICY`를 가진 경우 fail-closed 한다.
|
||||
- MCP `search_hr_data`만 새 경계로 전환하며 용어·정책 검색 도구는 기존 경로를 유지한다.
|
||||
|
||||
## 구조
|
||||
## 전체 구성
|
||||
|
||||
```text
|
||||
MCP tools/call
|
||||
└─ bearer token 해시 인증
|
||||
├─ ADMIN / DBMS_CLOUD_AI.GENERATE(..., 'showsql')
|
||||
│ └─ 허용된 HMM HR 객체만 포함한 SELECT/WITH 생성
|
||||
└─ CB_ORDS JDBC session
|
||||
├─ CB_ORDS_HANDLER_PKG.SET_VPD_CONTEXT('Bearer ...')
|
||||
│ └─ ADMIN.HMM_ACCESS_CTX_PKG.SET_USER_BY_BEARER(token)
|
||||
├─ runtime principal/컨텍스트 일치 검증
|
||||
├─ SET TRANSACTION READ ONLY
|
||||
├─ 생성 SQL 실행 → HMM_LEAVE_SCOPE_POLICY 적용
|
||||
├─ ROLLBACK
|
||||
└─ CB_ORDS_HANDLER_PKG.CLEAR_VPD_CONTEXT
|
||||
포털 사용자 preset
|
||||
→ 사용자별 Bearer token
|
||||
→ token hash로 EMPLOYEE_ID 확인
|
||||
→ ADMIN Select AI SHOWSQL 생성
|
||||
→ CB_ORDS 연결에서 SET_VPD_CONTEXT
|
||||
→ 생성 SELECT 실행
|
||||
→ HMM_CARRIER_ASSIGNMENTS_V VPD
|
||||
├─ E1001 팀장: 직속 팀원 배정 8건
|
||||
└─ E1002 팀원: 본인 배정 C001·C002 2건
|
||||
→ 허용된 CARRIER_CODE만 원격 KPI와 조인
|
||||
→ HTML renderer
|
||||
```
|
||||
|
||||
## DB 설계
|
||||
핵심은 token 소유자, DB context의 직원, VPD predicate가 동일한 요청 안에서 이어지는 것이다.
|
||||
`SET_VPD_CONTEXT`를 호출해도 `EXEMPT ACCESS POLICY`를 가진 연결에서 SELECT하면 정책이 우회된다.
|
||||
|
||||
### 런타임 스키마
|
||||
## 현재 상태
|
||||
|
||||
`CB_ORDS`에는 다음 최소 권한만 부여한다.
|
||||
2026-08-10 운영 적용 및 MCP 호출 검증을 완료했다.
|
||||
|
||||
- `CREATE SESSION`
|
||||
- `ADMIN.CB_ORDS_HANDLER_PKG` 실행
|
||||
- Select AI 프로필의 승인 객체 6개에 대한 `SELECT`
|
||||
- `HMM_ORG_TEAMS`
|
||||
- `HMM_HR_EMPLOYEES`
|
||||
- `HMM_LEAVE_BALANCES`
|
||||
- `HMM_LEAVE_REQUESTS`
|
||||
- `HMM_ATTENDANCE_DAILY`
|
||||
- `HMM_HR_TERMS`
|
||||
- 사용자별 portal token 5개가 서로 다른 hash로 직원에게 연결됨
|
||||
- `HMM_CARRIER_SCOPE_POLICY` 활성화
|
||||
- MCP E1001: `vpdEnforced=true`, 8건
|
||||
- MCP E1002: `vpdEnforced=true`, 2건, 직원 범위 E1002만 포함
|
||||
- E1002 renderer: 입력 2건, HTML에 C001·C002 포함, E1003 미포함
|
||||
- 동일 E1002 조회와 renderer를 두 번 연속 호출해 두 호출 모두 표준 컬럼 9개와 HTML 2건을 확인
|
||||
|
||||
`EXEMPT ACCESS POLICY`, `SELECT ANY TABLE`, 객체 생성 `ANY` 권한은 부여하지 않는다.
|
||||
생성 SQL의 스키마 한정 여부에 영향을 받지 않도록 승인 객체에 한해
|
||||
`CB_ORDS` private synonym을 만든다.
|
||||
## 문서 지도
|
||||
|
||||
### 컨텍스트 패키지
|
||||
|
||||
`ADMIN.CB_ORDS_HANDLER_PKG`는 HTTP Authorization 값에서 Bearer 토큰을
|
||||
추출한 후 `ADMIN.HMM_ACCESS_CTX_PKG.SET_USER_BY_BEARER`를 호출한다.
|
||||
토큰 원문은 테이블이나 로그에 저장하지 않는다.
|
||||
|
||||
`CB_ORDS`에는 동일 이름의 private synonym만 제공하여 런타임 SQL에서는
|
||||
`CB_ORDS_HANDLER_PKG.SET_VPD_CONTEXT`로 호출한다. 컨텍스트 패키지 자체의
|
||||
직접 실행 권한은 런타임 계정에 노출하지 않는다.
|
||||
|
||||
`CLEAR_VPD_CONTEXT`는 HMM 컨텍스트와 client identifier를 모두 정리한다.
|
||||
유효하지 않은 인증 헤더는 컨텍스트를 먼저 지운 뒤 오류로 종료한다.
|
||||
|
||||
## 애플리케이션 설계
|
||||
|
||||
`backoffice.select-ai` 설정을 두 연결로 분리한다.
|
||||
|
||||
- 생성 연결: 기존 `db-url`, `db-username`, `db-password`, `profile`
|
||||
- 실행 연결: `runtime-db-url`, `runtime-db-username`, `runtime-db-password`
|
||||
|
||||
생성 연결은 기존 `BACKOFFICE_DB_*`를 기본값으로 사용할 수 있다. 실행 연결은
|
||||
명시적으로 설정해야 하며 생성 연결로 자동 폴백하지 않는다.
|
||||
|
||||
실행 전 다음을 검증한다.
|
||||
|
||||
1. `USER`가 `ADMIN`이 아니다.
|
||||
2. `SESSION_PRIVS`에 `EXEMPT ACCESS POLICY`가 없다.
|
||||
3. 패키지 호출 후 `HMM_ACCESS_CTX.EMPLOYEE_CODE`가 토큰 인증 결과와 일치한다.
|
||||
|
||||
하나라도 실패하면 SQL을 실행하지 않는다.
|
||||
|
||||
## 운영 설정
|
||||
|
||||
`search_hr_data`의 `executionType`을 `AGENT_TOOL`에서 `SELECT_AI`로 변경한다.
|
||||
다른 두 도구는 그대로 유지한다.
|
||||
|
||||
필수 환경값:
|
||||
|
||||
```properties
|
||||
BACKOFFICE_SELECT_AI_PROFILE=HMM_HR_DATA_GPT54_PROFILE
|
||||
BACKOFFICE_SELECT_AI_RUNTIME_DB_URL=<ADB JDBC URL>
|
||||
BACKOFFICE_SELECT_AI_RUNTIME_DB_USERNAME=CB_ORDS
|
||||
BACKOFFICE_SELECT_AI_RUNTIME_DB_PASSWORD=<secret>
|
||||
```
|
||||
|
||||
비밀번호는 Git·Redmine·로그에 기록하지 않고 서버 환경 파일에서만 관리한다.
|
||||
|
||||
## 검증 기준
|
||||
|
||||
1. `CB_ORDS`에 `EXEMPT ACCESS POLICY`가 없음을 확인한다.
|
||||
2. E1006 토큰으로 `HMM_LEAVE_BALANCES` 조회 결과의 직원은 E1006 한 명뿐이다.
|
||||
3. E1006 토큰으로 `HMM_LEAVE_REQUESTS` 조회 결과에 E1002가 없다.
|
||||
4. E1006이 E1002 휴가를 직접 요청하면 0건을 반환한다.
|
||||
5. 관리자 E1001은 권한 규칙에 따라 자기 자신과 직속 팀원 범위를 조회한다.
|
||||
6. 무효 토큰, 컨텍스트 불일치, 런타임 권한 오설정은 fail-closed 한다.
|
||||
|
||||
## 롤백
|
||||
|
||||
- 애플리케이션 환경의 `search_hr_data`를 이전 `AGENT_TOOL` 정의로 되돌리고
|
||||
이전 JAR를 재기동한다.
|
||||
- `CB_ORDS` 스키마는 즉시 삭제하지 않고 계정을 잠가 조사 가능 상태로 보존한다.
|
||||
- VPD 정책 자체와 기존 `HMM_ACCESS_CTX_PKG`는 변경하지 않는다.
|
||||
- [아키텍처와 신뢰 경계](architecture.md)
|
||||
- [적용 및 검증 절차](cookbook.md)
|
||||
- [문제 해결](troubleshooting.md)
|
||||
- [HTML 리포트 후속 처리](../hmm-html-report-mcp/README.md)
|
||||
|
||||
56
docs/design/740-hmm-mcp-vpd-runtime/architecture.md
Normal file
56
docs/design/740-hmm-mcp-vpd-runtime/architecture.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# HMM MCP VPD 아키텍처
|
||||
|
||||
[개요](README.md) · [적용 절차](cookbook.md) · [문제 해결](troubleshooting.md)
|
||||
|
||||
## 권한 흐름
|
||||
|
||||
```text
|
||||
포털 사용자 preset
|
||||
→ 사용자별 Bearer token
|
||||
→ token hash로 EMPLOYEE_ID 식별
|
||||
→ HMM_ACCESS_CTX.EMPLOYEE_ID 설정
|
||||
→ Select AI가 만든 SELECT를 CB_ORDS에서 실행
|
||||
→ HMM_CARRIER_ASSIGNMENTS_V VPD
|
||||
├─ VIEWER: 본인 EMPLOYEE_ID
|
||||
└─ MANAGER: 본인과 직속 팀원 EMPLOYEE_ID
|
||||
→ 허용된 CARRIER_CODE만 원격 선사 실적과 조인
|
||||
→ HTML renderer
|
||||
```
|
||||
|
||||
선사 조회의 자연어 처리와 `CARRIER_CODE` 조인은 기존 Select AI 프로필을 유지한다. 권한 조건을
|
||||
질문이나 고정 SQL에 넣지 않고 Oracle VPD가 세션 사용자 ID로 자동 적용한다.
|
||||
|
||||
## 출력 스키마 계약
|
||||
|
||||
Select AI는 같은 의미의 컬럼도 호출마다 `CARRIER_CODE`, `carrier Code`, `선사코드`처럼 다른
|
||||
alias로 생성할 수 있다. `vpd-backoffice/config/hmm_carrier_query_contract.json`은 SQL을 고정하지
|
||||
않고 다음 결과 alias만 고정한다.
|
||||
|
||||
```text
|
||||
EMPLOYEE_CODE, EMPLOYEE_NAME, MANAGER_EMPLOYEE_CODE,
|
||||
CARRIER_CODE, CARRIER_NAME, LATEST_REVENUE_USD,
|
||||
LATEST_GROSS_MARGIN_USD, LATEST_SCHEDULE_RELIABILITY_PCT,
|
||||
LATEST_RISK_LEVEL
|
||||
```
|
||||
|
||||
따라서 권한에 따라 행 수는 달라져도 renderer에 전달되는 행 구조는 매 호출 동일하다.
|
||||
|
||||
## 신뢰 경계
|
||||
|
||||
- 화면에 표시된 사용자 코드는 권한 근거가 아니다. 선택 preset의 전용 Bearer token이 근거다.
|
||||
- 토큰 원문은 서버 환경에만 저장하고 DB에는 SHA-256 hash만 저장한다.
|
||||
- `ADMIN`은 `EXEMPT ACCESS POLICY`가 있으므로 SQL 생성만 수행한다.
|
||||
- 실제 SELECT는 비면제 계정 `CB_ORDS`가 같은 요청의 VPD context를 설정한 뒤 실행한다.
|
||||
- renderer는 이미 필터링된 행만 표현하며 사용자나 권한을 다시 판단하지 않는다.
|
||||
|
||||
## 선사 VPD 규칙
|
||||
|
||||
보호 객체는 `ADMIN.HMM_CARRIER_ASSIGNMENTS_V`, 기준 컬럼은 `EMPLOYEE_ID`다.
|
||||
|
||||
| 역할 | 규칙 | 적용 범위 |
|
||||
|---|---|---|
|
||||
| `HMM_HR_VIEWER` | `SELF` | 현재 인증 사용자 |
|
||||
| `HMM_HR_MANAGER` | `MANAGED_TEAM` | 현재 사용자와 직속 팀원 |
|
||||
| `HMM_HR_ADMIN` | `ALL` | 명시적 관리자 전체 |
|
||||
|
||||
컨텍스트, 활성 역할 또는 허용 규칙이 없으면 `1=0`으로 차단한다.
|
||||
28
docs/design/740-hmm-mcp-vpd-runtime/cookbook.md
Normal file
28
docs/design/740-hmm-mcp-vpd-runtime/cookbook.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# HMM MCP VPD 적용 절차
|
||||
|
||||
[개요](README.md) · [아키텍처](architecture.md) · [문제 해결](troubleshooting.md)
|
||||
|
||||
1. `ADMIN`이 VPD 우회 권한을 가지고 `CB_ORDS`는 가지지 않는지 확인한다.
|
||||
2. `database/adb/84_hmm_carrier_team_vpd.sql`을 ADMIN으로 실행한다.
|
||||
3. 포털 preset마다 `HMM_MCP_BEARER_TOKEN_<EMPLOYEE_CODE>` 전용 토큰을 발급한다.
|
||||
4. 선사 조회 MCP는 기존 `HMM_RDS_FEDERATION_PROFILE`로 `SHOWSQL`을 생성하고 `CB_ORDS`에서 실행한다.
|
||||
운영 도구 정의는 이름과 입력 계약을 유지하고 `executionType`만 `SELECT_AI`로 설정한다.
|
||||
`BACKOFFICE_SELECT_AI_QUERY_CONTRACT_FILE`에는 배포한
|
||||
`config/hmm_carrier_query_contract.json`의 절대 경로를 설정한다.
|
||||
5. 서비스를 재시작하고 동일 질문을 E1001과 E1002로 각각 호출한다.
|
||||
|
||||
성공 기준:
|
||||
|
||||
| 사용자 | 허용된 선사 배정 | 예상 건수 |
|
||||
|---|---|---:|
|
||||
| E1001 팀장 | 직속 팀원 C001~C008 | 8 |
|
||||
| E1002 팀원 | 본인 C001, C002 | 2 |
|
||||
|
||||
첫 조회 결과, renderer 입력, HTML 표의 행 수와 직원 범위가 모두 같아야 한다. 토큰 원문과 DB
|
||||
비밀번호는 명령·로그·문서에 출력하지 않는다.
|
||||
|
||||
MCP 응답에서 `vpdEnforced=true`, `scopeEmployeeCode`가 선택 사용자와 같은지도 확인한다.
|
||||
같은 E1002 질문을 두 번 실행해 두 응답 모두 표준 alias 9개와 C001·C002 두 행을 반환하는지 확인한다.
|
||||
|
||||
롤백할 때는 VPD 정책을 삭제하지 말고 disable하여 조사 가능 상태로 보존한다. 사용자별 token
|
||||
환경변수도 공용 token으로 되돌리지 않고 사용자 선택 기능을 일시 비활성화한다.
|
||||
27
docs/design/740-hmm-mcp-vpd-runtime/troubleshooting.md
Normal file
27
docs/design/740-hmm-mcp-vpd-runtime/troubleshooting.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# HMM MCP VPD 문제 해결
|
||||
|
||||
[개요](README.md) · [아키텍처](architecture.md) · [적용 절차](cookbook.md)
|
||||
|
||||
## 사용자를 바꿔도 같은 결과
|
||||
|
||||
- 원인: preset들이 같은 token 환경변수를 참조하거나 선사 View에 VPD가 없다.
|
||||
- 확인: token 원문을 출력하지 않고 preset 환경변수 이름과 token hash의 employee mapping을 확인한다.
|
||||
- 해결: 사용자별 token을 발급하고 `HMM_CARRIER_SCOPE_POLICY`를 활성화한다.
|
||||
|
||||
## 컨텍스트는 다른데 전체 행이 보임
|
||||
|
||||
- 원인: 최종 SELECT가 `EXEMPT ACCESS POLICY`를 가진 ADMIN에서 실행됐다.
|
||||
- 확인: 실행 계정의 `SESSION_PRIVS`와 MCP 응답의 `scopeEmployeeCode`를 확인한다.
|
||||
- 해결: ADMIN은 Select AI `SHOWSQL`만 수행하고 실제 SELECT는 `CB_ORDS`에서 실행한다.
|
||||
|
||||
## 팀원 결과가 0건
|
||||
|
||||
- 원인: token→직원, 직원→역할, 직원→선사 access group 중 하나가 누락됐다.
|
||||
- 확인: 위 순서로 원장 연결을 확인한다.
|
||||
- 해결: 누락된 원장만 보강한다. 조회 함수에 직원 코드나 결과 행을 하드코딩하지 않는다.
|
||||
|
||||
## 원격 선사 KPI가 과다 노출됨
|
||||
|
||||
- 원인: 생성 SQL이 로컬 `HMM_CARRIER_ASSIGNMENTS_V` 없이 원격 KPI View만 읽었다.
|
||||
- 해결: Select AI profile metadata에서 직원·팀 질의는 배정 View와 KPI View를 `CARRIER_CODE`로
|
||||
조인하도록 유지한다. SQL 자체는 고정하지 않는다.
|
||||
61
docs/design/744-windows-ad-dds-end-user-mapping/README.md
Normal file
61
docs/design/744-windows-ad-dds-end-user-mapping/README.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Windows AD → OCI IAM → DDS 권한 매핑 (#744)
|
||||
|
||||
> **상태**: Keycloak 기반 Alice 허용/Bob 기본 거부 검증 완료 · OCI IAM AD Bridge 전환 진행 중
|
||||
> **최종수정**: 2026-08-05
|
||||
|
||||
## 한눈에 보기
|
||||
|
||||
Windows AD의 계정으로 AIPF MCP에 로그인하고, Oracle Deep Sec(DDS)이 사용자마다 다른 데이터를 보이도록 하는 PoC다. 초기에는 Keycloak이 AD 인증을 OIDC token으로 바꿨다. 현재는 Keycloak을 OCI Identity Domain의 **AD Bridge + delegated authentication**으로 대체하는 중이다.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U["AD 사용자<br/>Alice / Bob"] --> A["Windows AD DS<br/>계정·비밀번호 원천"]
|
||||
A <--> B["OCI AD Bridge<br/>동기화·인증 위임"]
|
||||
B <--> I["OCI Identity Domain<br/>SSO·OIDC token 발급"]
|
||||
I --> P["AIPF<br/>MCP OAuth 연결"]
|
||||
P --> M["DDS MCP<br/>JWT 검증·사용자 매핑"]
|
||||
M --> D["Oracle DDS<br/>DATA GRANT 집행"]
|
||||
```
|
||||
|
||||
이 그림에서 기억할 점: **AD는 비밀번호를 확인하고, OCI Identity Domain은 로그인 화면과 JWT를 발급하며, Oracle DDS는 최종 데이터 권한을 강제한다.** AD Bridge는 그 사이를 연결하는 Windows 서비스다.
|
||||
|
||||
## 현재 검증 결과
|
||||
|
||||
| 항목 | 결과 |
|
||||
|---|---|
|
||||
| Keycloak → MCP → DDS 경로 | 완료 |
|
||||
| `dds-alice`의 `휴가` 검색 | `휴가 정책 - Alice 전용 테스트` 1건 반환 |
|
||||
| `dds-bob`의 같은 검색 | DATA GRANT 없음으로 default deny (`ORA-00942` 은닉) |
|
||||
| OCI AIPF OAuth client | `AIPF_DDS_AD_TEST` 생성 및 OIDC discovery 확인 완료 |
|
||||
| OCI AD Bridge client / AD 동기화 | 설치 완료 · Alice/Bob 2명과 `DDS-DDS-Users` 1개 import 성공 |
|
||||
| OCI delegated authentication | **차단**: 이 Identity Domain에서 기능이 beta 미활성화 상태. OCI tenancy enablement 필요 |
|
||||
|
||||
## 핵심 결정
|
||||
|
||||
1. 사용자 token과 DB service token은 분리한다.
|
||||
- 사용자 token: 누가 MCP를 호출했는가
|
||||
- DB service token: MCP service가 DDS context를 열 수 있는가
|
||||
2. 사람별 권한 키는 검증된 `issuer + sub`이며, UPN/email은 표시·감사용이다.
|
||||
3. DB 권한은 MCP가 아닌 Oracle DDS DATA ROLE/DATA GRANT에서 default deny로 집행한다.
|
||||
4. OCI 전환은 기존 Keycloak을 즉시 제거하지 않고, OCI 경로의 Alice/Bob 결과가 같은지 확인한 뒤에만 완료한다.
|
||||
|
||||
## 문서 지도
|
||||
|
||||
| 필요한 경우 | 읽을 문서 |
|
||||
|---|---|
|
||||
| 전체 신뢰 경계, token 두 종류, DB/DDS 매핑 구조를 이해할 때 | [아키텍처 상세](architecture.md) |
|
||||
| OCI AD Bridge 설치, OCI OAuth client 등록, AIPF/MCP 전환을 수행할 때 | [적용 Cookbook](cookbook.md) |
|
||||
| 로그인·callback·token·LDAPS·권한 오류를 진단할 때 | [트러블슈팅](troubleshooting.md) |
|
||||
| 저장소 전체 문서 작성 구조를 확인할 때 | [문서 구조 표준](../../DOCUMENTATION-STANDARDS.md) |
|
||||
|
||||
## 전환 완료 기준
|
||||
|
||||
- OCI AD Bridge가 `dds-alice`, `dds-bob`과 필요한 AD 그룹을 동기화한다.
|
||||
- OCI tenancy에서 delegated authentication capability가 enable된 뒤, OCI Identity Domain login이 두 사용자의 **AD 비밀번호**로 delegated authentication을 통과한다.
|
||||
- AIPF가 OCI OAuth login 후 MCP에 연결된다.
|
||||
- OCI JWT의 `issuer + sub`가 각각 `DDS_U_1`, `DDS_U_2`로 매핑된다.
|
||||
- 동일한 `휴가` 검색에서 Alice는 1건을 받고 Bob은 default deny가 유지된다.
|
||||
|
||||
## 보안 원칙
|
||||
|
||||
AD 사용자 비밀번호, OAuth client secret, OCI service client secret, access/refresh token은 문서·Git·대화에 적지 않는다. 위치, rotation 절차, 안전한 입력 방법만 [Cookbook](cookbook.md)에 기록한다.
|
||||
722
docs/design/744-windows-ad-dds-end-user-mapping/architecture.md
Normal file
722
docs/design/744-windows-ad-dds-end-user-mapping/architecture.md
Normal file
@@ -0,0 +1,722 @@
|
||||
# 설계서: Windows AD 기반 DDS END USER 매핑 테스트 (#744)
|
||||
|
||||
> **상태**: Keycloak 기반 검증 완료 · OCI IAM AD Bridge + delegated authentication 전환 진행 중
|
||||
> **최종수정**: 2026-08-05
|
||||
> **추적성**: Redmine #744 · 선행 설계: [DDS MCP END USER Context](../617-dds-mcp-end-user-context/README.md)
|
||||
|
||||
[개요로 돌아가기](README.md) · [적용 Cookbook](cookbook.md) · [트러블슈팅](troubleshooting.md)
|
||||
|
||||
## 1. 목적과 범위
|
||||
|
||||
Microsoft Entra ID 테넌트가 아직 준비되지 않은 상황에서, OCI 격리 네트워크의 Windows Server AD DS를 이용해 업무 사용자 디렉터리와 DDS END USER 매핑을 먼저 검증한다.
|
||||
|
||||
이 환경은 **Microsoft Entra access token을 Oracle DB가 직접 검증하는 환경이 아니다.** AD DS는 사용자·그룹·UPN을 제공하고, 이후 Keycloak 또는 별도 검증 서비스가 AD LDAP을 기반으로 발급·검증한 토큰의 안정적인 subject를 MCP의 업무 사용자로 해석한다. Entra tenant와 app registration이 준비되면 OIDC issuer/audience/JWKS 검증 경로로 교체 또는 병행한다.
|
||||
|
||||
### 2026-08-05: OCI IAM AD Bridge 전환 목표
|
||||
|
||||
초기 PoC는 AD DS를 OIDC로 연결하기 위해 Keycloak을 사용했다. 이제 OCI Identity Domain의 **Microsoft Active Directory (AD) Bridge**와 **delegated authentication**을 사용해 Keycloak을 대체한다. AD DS는 계속 사용자·비밀번호의 원천이며, OCI Identity Domain이 AD Bridge를 통해 AD 비밀번호를 확인한 후 AIPF/MCP용 OIDC token을 발급한다.
|
||||
|
||||
```text
|
||||
기존: AD DS → Keycloak → Keycloak user JWT → MCP → DDS
|
||||
전환: AD DS → OCI AD Bridge + delegated authentication
|
||||
→ OCI Identity Domain user JWT → MCP → DDS
|
||||
```
|
||||
|
||||
이미 운영 중인 OCI database resource application `DDS_ORACLE_DB_TEST`와 DB service client `DDS_MCP_SERVICE_TEST`는 제거하거나 사용자 로그인 client로 재사용하지 않는다. 이들은 MCP가 Oracle DB DDS context를 여는 **machine-to-machine** 신뢰에 계속 사용한다. 사용자 로그인에는 별도의 OCI confidential OAuth application을 만든다.
|
||||
|
||||
#### 전환 원칙
|
||||
|
||||
1. Keycloak, 기존 mapping, 기존 AIPF source는 OCI 경로 검증 전까지 유지한다.
|
||||
2. OCI AD Bridge가 AD 사용자·그룹을 동기화하고 delegated authentication으로 `dds-alice`/`dds-bob`의 **AD 비밀번호**를 확인하는 것을 먼저 검증한다.
|
||||
3. AIPF 전용 OCI OAuth client를 별도로 만든다. callback URI와 refresh token 사용은 기존 AIPF 호환 설정을 유지한다.
|
||||
4. MCP는 OCI Identity Domain의 discovery/JWKS, issuer, audience로 검증 대상을 바꾼다. Keycloak token과 OCI token을 동시에 허용하지 않는다.
|
||||
5. OCI token의 검증된 `iss + sub`를 별도 binding으로 Alice=`DDS_U_1`, Bob=`DDS_U_2`에 등록한다.
|
||||
6. OCI 경로에서 Alice 1건 반환과 Bob default deny를 확인한 뒤에만 Keycloak source와 DNS/VM 정리 여부를 결정한다.
|
||||
|
||||
#### 현재 전환 인벤토리
|
||||
|
||||
| 항목 | 현재 값/상태 | 전환 시 처리 |
|
||||
|---|---|---|
|
||||
| Windows AD DS | `dds.test`, `hmm-ad-dss-test-isolated`, 실행 중 | AD 사용자 원천으로 유지 |
|
||||
| OCI Identity Domain | `identityAPAC`, 활성 | AD Bridge와 사용자 OAuth client를 이 Domain에 추가 |
|
||||
| DB resource app | `DDS_ORACLE_DB_TEST` | 유지 |
|
||||
| DB service client | `DDS_MCP_SERVICE_TEST` | 유지 |
|
||||
| 사용자 OIDC issuer | Keycloak `https://ad.cloud-handson.com/realms/dds-test` | OCI Domain issuer로 교체 |
|
||||
| AIPF OAuth client | Keycloak `aipf-dds-mcp` | OCI Domain의 새 confidential client로 교체 |
|
||||
| MCP public endpoint | `https://hmm-backoffice.cloud-handson.com/mcp/dds/sse` | 유지 |
|
||||
| DDS local users/data grants | `DDS_U_1` 허용, `DDS_U_2` grant 없음 | 유지 |
|
||||
|
||||
#### OCI AD Bridge 구축 절차
|
||||
|
||||
1. `identityAPAC`의 **Directory integrations**에서 Microsoft AD Bridge를 생성한다.
|
||||
2. OCI가 표시하는 Domain URL, Bridge client ID/secret을 기록하고 Bridge client installer를 내려받는다. 이 client secret은 AIPF OAuth client secret과 다르며, Windows Bridge client 설정에만 사용한다.
|
||||
3. AD domain에 join된 Windows VM에 Bridge client를 설치한다. 운영은 Domain Controller와 별도 member server를 권장하지만, 이 격리 PoC는 기존 AD VM에서 설치 가능 여부를 우선 검증한다.
|
||||
4. Bridge service account에는 동기화 대상 OU/그룹에 대한 read 권한과 `cn=Deleted Objects` 읽기 권한을 준다. delegated authentication도 사용할 경우 Oracle이 요구하는 password/lockout attribute 권한을 최소 범위로 부여한다.
|
||||
5. LDAPS(636)를 사용하도록 구성하고, Bridge VM에서 OCI Domain HTTPS 443 및 AD LDAP/LDAPS 연결을 확인한다.
|
||||
6. `dds-alice`, `dds-bob`이 포함된 OU와 필요한 AD 그룹만 동기화 대상으로 선택한다.
|
||||
7. OCI console의 **Delegated authentication**에서 Bridge를 시험하고 활성화한다. 성공하면 OCI 로그인 화면의 password 검증은 AD에서 수행한다.
|
||||
8. AIPF용 OCI confidential OAuth application을 생성하고, AIPF callback URI, authorization-code/refresh-token grant, `openid` scope를 설정한다.
|
||||
9. OCI discovery document의 issuer/JWKS와 token의 `aud`, `sub`를 확인한 뒤 MCP runtime과 `CB_EXTERNAL_IDENTITY_BINDING`을 교체한다.
|
||||
|
||||
#### 전체 구성도: AD 계정 로그인부터 DDS 권한 적용까지
|
||||
|
||||
아래 구성에서 AD에 새로 붙는 구성요소는 **OCI IAM AD Bridge Client**다. 이는 AD Domain Controller 내부의 AD DS를 대체하거나 AD 비밀번호를 복제하는 서버가 아니다. Domain-joined Windows에 설치되는 Windows service로서, AD에는 LDAP/LDAPS로 연결하고 OCI Identity Domain에는 HTTPS 443으로 연결한다.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph USER[사용자·클라이언트]
|
||||
U["업무 사용자<br/>dds-alice / dds-bob"]
|
||||
AIPF["AIPF<br/>MCP OAuth client"]
|
||||
end
|
||||
|
||||
subgraph ADNET[OCI 격리 네트워크 · dds.test]
|
||||
AD["Windows Server 2022<br/>AD DS Domain Controller<br/>계정·비밀번호·그룹 원천"]
|
||||
BRIDGE["OCI IAM AD Bridge Client<br/>Windows service<br/>사용자/그룹 동기화 + 인증 위임"]
|
||||
AD -->|"LDAP 또는 LDAPS<br/>사용자·OU·그룹 읽기"| BRIDGE
|
||||
BRIDGE -->|"delegated authentication<br/>AD 비밀번호 확인 요청"| AD
|
||||
end
|
||||
|
||||
subgraph OCIID[OCI Identity Domain · identityAPAC]
|
||||
DOMAIN["OCI Identity Domain<br/>사용자 디렉터리·SSO·OIDC issuer"]
|
||||
OAUTH["AIPF_DDS_AD_TEST<br/>confidential OAuth client<br/>authorization_code + refresh_token"]
|
||||
DBAPP["DDS_ORACLE_DB_TEST<br/>database resource / integrated app<br/>DB_ACCESS_SCOPE"]
|
||||
SVC["DDS_MCP_SERVICE_TEST<br/>confidential service client<br/>client_credentials only"]
|
||||
DOMAIN --- OAUTH
|
||||
DOMAIN --- DBAPP
|
||||
DOMAIN --- SVC
|
||||
end
|
||||
|
||||
BRIDGE -->|"HTTPS 443<br/>AD 사용자·그룹 동기화"| DOMAIN
|
||||
U -->|"1. AIPF에서 MCP 연결"| AIPF
|
||||
AIPF -->|"2. OAuth authorization code"| OAUTH
|
||||
OAUTH -->|"3. AD 비밀번호 검증 위임"| BRIDGE
|
||||
OAUTH -->|"4. OCI user access token<br/>iss + aud + sub"| AIPF
|
||||
|
||||
subgraph MCPHOST[HMM Backoffice VM]
|
||||
MCP["DDS MCP Server<br/>hmm-backoffice.cloud-handson.com<br/>/mcp/dds/sse"]
|
||||
JWT["JWT 검증<br/>OCI discovery / JWKS<br/>issuer + audience + exp"]
|
||||
MAP["Identity binding<br/>OCI iss + sub<br/>→ CB_APP_USER → DDS_U_n"]
|
||||
DBTOKEN["DB service token 획득<br/>client credentials"]
|
||||
MCP --> JWT --> MAP
|
||||
MCP --> DBTOKEN
|
||||
end
|
||||
|
||||
AIPF -->|"5. Authorization: Bearer<br/>OCI user access token"| MCP
|
||||
MCP -->|"6. discovery/JWKS HTTPS"| DOMAIN
|
||||
DBTOKEN -->|"7. client ID + secret<br/>DB_ACCESS_SCOPE"| SVC
|
||||
SVC -->|"8. database-access token"| DBTOKEN
|
||||
|
||||
subgraph ADB[Oracle Autonomous Database · HMMAIPOC]
|
||||
APPID["DB application identity<br/>DDS_MCP_SERVICE_TEST 신뢰"]
|
||||
CTX["ORA_END_USER_CONTEXT<br/>DDS_U_1 또는 DDS_U_2 attach"]
|
||||
DDS["Oracle Deep Sec<br/>DATA ROLE / DATA GRANT<br/>default deny"]
|
||||
DATA["CB_VECTOR_SEARCH_DOCUMENTS<br/>보호 데이터"]
|
||||
APPID --> CTX --> DDS --> DATA
|
||||
end
|
||||
|
||||
DBTOKEN -->|"9. database-access token"| APPID
|
||||
MAP -->|"10. 선택된 local END USER"| CTX
|
||||
DATA -->|"11. 허용된 행만"| MCP
|
||||
MCP -->|"12. tool result"| AIPF
|
||||
```
|
||||
|
||||
| 번호 | 구간 | 전달되는 것 | 보안 의미 |
|
||||
|---:|---|---|---|
|
||||
| 1~4 | 사용자 → AIPF → OCI Domain → AD Bridge → AD | AD 사용자명·비밀번호, OAuth code, OCI user token | AD는 비밀번호 원천으로 남고 OCI Domain이 OIDC issuer 역할 수행 |
|
||||
| 5~6 | AIPF → MCP → OCI Domain | Bearer user JWT, JWKS/discovery | MCP가 서명·issuer·audience·만료를 검증해 사용자 위조 차단 |
|
||||
| 7~9 | MCP → OCI Domain → DB | service client credentials, DB 전용 access token | MCP process만 DB context를 열 수 있음; user JWT를 DB service token으로 쓰지 않음 |
|
||||
| 10~12 | MCP → DB DDS → AIPF | local DDS END USER, 필터된 query 결과 | Alice/Bob 권한은 DB DATA GRANT에서 최종 강제 |
|
||||
|
||||
#### AD Bridge가 하는 일과 하지 않는 일
|
||||
|
||||
| AD Bridge가 하는 일 | AD Bridge가 하지 않는 일 |
|
||||
|---|---|
|
||||
| AD OU의 사용자·그룹 변경을 OCI Domain으로 동기화 | AD Domain Controller 또는 LDAP 서버를 대체하지 않음 |
|
||||
| OCI Domain의 delegated authentication 요청을 AD에 전달해 AD 비밀번호를 검증 | AD 사용자 비밀번호를 MCP나 AIPF에 전달하지 않음 |
|
||||
| AD 계정 비활성화·그룹 변경을 OCI user 상태/그룹과 동기화 | AIPF OAuth client secret 또는 DB service client secret을 보관하지 않음 |
|
||||
| OCI Domain과 AD 사이의 제한된 연결을 담당 | Oracle DB의 DDS data grant를 평가하거나 우회하지 않음 |
|
||||
|
||||
Bridge 설치 위치는 운영에서는 AD Domain Controller와 분리한 domain-joined Windows member server가 원칙이다. 이 PoC는 격리된 단일 Windows VM이므로 동일 VM 설치 가능성을 확인하되, 결과 문서에는 이 제약을 남긴다. Bridge VM에는 OCI Domain으로의 outbound HTTPS 443과 AD DS로의 LDAP/LDAPS 389/636만 허용한다.
|
||||
|
||||
#### 적용 가이드: OCI AD Bridge와 AIPF OAuth client
|
||||
|
||||
이 절은 다음 환경에서 재적용할 때 사용하는 runbook이다. 명령의 secret 값은 출력하거나 Git에 넣지 않는다.
|
||||
|
||||
##### 1. 사전 점검
|
||||
|
||||
| 점검 | 기대값 | 실패 시 조치 |
|
||||
|---|---|---|
|
||||
| OCI Identity Domain | `identityAPAC` 등 대상 Domain이 `ACTIVE` | Domain 관리자 권한 및 Domain type/AD Bridge 허용량 확인 |
|
||||
| AD DS | `dds.test` Domain Controller와 DNS·LDAP 정상 | Bridge를 Domain-joined Windows에 설치할 수 있는지 확인 |
|
||||
| 네트워크 | Bridge VM → OCI Domain TCP/443, Bridge VM → AD TCP/636(LDAPS 권장) | NSG, Windows Firewall, proxy, AD 인증서 점검 |
|
||||
| AD service account | 동기화 OU 읽기 및 delegated authentication에 필요한 최소 attribute 권한 | Domain Admin을 상시 사용하지 말고 전용 service account 생성 |
|
||||
| AIPF callback | `https://aipf.cloud-handson.com/agentFactory/v1/tools/mcp/callback` 및 `/v1/tools/mcp/callback` | 두 URL 모두 OCI OAuth client redirect URI에 등록 |
|
||||
|
||||
현재 PoC의 Windows VM은 `hmm-ad-dss-test-isolated`이며 실행 중이다. public WinRM HTTPS(5986)의 OCI NSG, Windows listener, Windows Firewall을 구성해 외부 `/wsman` endpoint와 `opc@dds.test` 원격 실행을 확인했다. 따라서 Bridge client 설치는 WinRM으로 자동화할 수 있다. OCI Run Command는 command가 `ACCEPTED`에 머무르는 제약이 남아 있으므로 설치 수단으로 사용하지 않는다. 이 관리 경로 상태는 AD Bridge 자체의 요구사항이 아니라 설치 자동화 방식의 제약이다.
|
||||
|
||||
##### 2. OCI AD Bridge 생성과 Windows 설치
|
||||
|
||||
1. OCI Console에서 **Identity & Security → Domains → 대상 Domain → Directory integrations → Add → Microsoft Active Directory Bridge**로 이동한다.
|
||||
2. 화면에서 표시되는 **Identity Domain URL, Bridge client ID, Bridge client secret**을 안전한 password manager/secret store에 보관한다. 이것은 AIPF OAuth client secret 및 DB service client secret과 다른 값이다.
|
||||
3. Bridge client installer를 내려받아 domain-joined Windows에 설치한다. 현재 PoC artifact는 `ad-id-bridge-23.2.92-2301160723.exe`이며, checksum과 안전한 전달 방법은 [Cookbook의 installer artifact 관리](cookbook.md#11-installer-artifact-관리)를 따른다.
|
||||
4. 설치 UI에서 위 OCI Domain URL/client ID/client secret 및 AD Bridge service account를 입력하고 연결을 시험한다.
|
||||
5. AD 연결은 **LDAPS 사용**을 선택한다. AD DS 인증서가 Bridge Windows trust store에서 신뢰되지 않으면 먼저 CA/서버 인증서를 배포한다. 설치 후 SSL 선택은 변경이 어렵다.
|
||||
6. Directory integrations 화면에서 동기화할 사용자 OU, 그룹 OU를 최소 범위로 선택한다. `dds-alice`, `dds-bob`과 필요한 역할 그룹이 포함돼야 한다.
|
||||
7. Bridge initial sync 후 OCI Domain Users/Groups에 두 사용자가 나타나는지 확인한다.
|
||||
8. **Security → Delegated authentication**에서 `Test Delegated Authentication`으로 AD 사용자명과 AD 비밀번호를 시험하고 성공한 뒤에만 활성화한다.
|
||||
|
||||
`dds-alice`/`dds-bob` 로그인은 계속 AD 계정으로 한다. OCI Domain에 동기화된 user 레코드는 SSO/OIDC subject를 위한 cloud-side representation이고, delegated authentication 활성화 뒤의 비밀번호 검증 원천은 AD DS다.
|
||||
|
||||
##### 3. AIPF용 OCI OAuth client 생성
|
||||
|
||||
OCI Domain에는 DB service client와 별도로 AIPF용 confidential client가 필요하다. 이 PoC에서 만든 application 이름은 `AIPF_DDS_AD_TEST`이며 다음 정책을 사용한다.
|
||||
|
||||
| 항목 | 적용값 |
|
||||
|---|---|
|
||||
| Application type | Confidential OAuth client (`CustomWebAppTemplateId`) |
|
||||
| Grants | `authorization_code`, `refresh_token` |
|
||||
| Refresh token | 허용 (`allowOffline=true`) |
|
||||
| Redirect URI | AIPF callback 2개 경로 |
|
||||
| Access token expiry | 3600초 |
|
||||
| Refresh token expiry | 1209600초(14일) |
|
||||
| Consent | PoC에서 bypass; 운영 전 사용자 동의/정책 검토 |
|
||||
|
||||
OCI CLI로 생성할 경우 Identity Domain App API의 필수 `basedOnTemplate`을 반드시 포함한다.
|
||||
|
||||
```json
|
||||
{
|
||||
"schemas": ["urn:ietf:params:scim:schemas:oracle:idcs:App"],
|
||||
"displayName": "AIPF_DDS_AD_TEST",
|
||||
"basedOnTemplate": {"value": "CustomWebAppTemplateId"},
|
||||
"active": true,
|
||||
"isOAuthClient": true,
|
||||
"clientType": "confidential",
|
||||
"allowedGrants": ["authorization_code", "refresh_token"],
|
||||
"redirectUris": [
|
||||
"https://aipf.cloud-handson.com/agentFactory/v1/tools/mcp/callback",
|
||||
"https://aipf.cloud-handson.com/v1/tools/mcp/callback"
|
||||
],
|
||||
"allowOffline": true
|
||||
}
|
||||
```
|
||||
|
||||
생성된 app ID/client ID/client secret은 local 검증 환경에서는 git-ignore된 `.runtime/aipf-dds-oci-ad-client.env`에만 저장한다. 파일에는 `OCI_AIPF_DDS_APP_ID`, `OCI_AIPF_DDS_CLIENT_ID`, `OCI_AIPF_DDS_CLIENT_SECRET`만 두며 값은 문서·Redmine·채팅·shell 출력에 기록하지 않는다.
|
||||
|
||||
##### 4. AIPF에 입력할 OCI OAuth 값
|
||||
|
||||
OCI OpenID discovery 문서에서 endpoint를 확인한다. URL을 임의로 조합하지 말고 아래 discovery endpoint의 실제 응답을 기준으로 한다.
|
||||
|
||||
```text
|
||||
https://<identity-domain>/.well-known/openid-configuration
|
||||
```
|
||||
|
||||
현재 `identityAPAC`에서 확인한 형식은 다음과 같다.
|
||||
|
||||
| AIPF 입력 항목 | 값 형식 |
|
||||
|---|---|
|
||||
| Server URL | `https://hmm-backoffice.cloud-handson.com/mcp/dds/sse` |
|
||||
| Authentication mode | `OAuth` |
|
||||
| OAuth client ID/secret | `AIPF_DDS_AD_TEST` 생성 결과의 client ID/secret |
|
||||
| Authorization URL | `https://idcs-<domain>.identity.oraclecloud.com:443/oauth2/v1/authorize` |
|
||||
| Token / Refresh URL | `https://idcs-<domain>.identity.oraclecloud.com:443/oauth2/v1/token` |
|
||||
| Scopes | `openid profile email offline_access` (실제 app policy에 맞춰 조정) |
|
||||
|
||||
##### 5. MCP 및 DB 매핑 전환
|
||||
|
||||
Bridge와 AIPF OAuth login을 검증한 뒤, OCI access token을 decode하여 `iss`, `aud`, immutable `sub`를 기록한다. 그 다음에만 다음 값을 교체한다.
|
||||
|
||||
| 대상 | 변경 |
|
||||
|---|---|
|
||||
| HMM MCP `DDS_MCP_OIDC_ISSUER_URI` | OCI discovery가 반환한 issuer (현재 확인값 `https://identity.oraclecloud.com/`) |
|
||||
| HMM MCP `DDS_MCP_OIDC_AUDIENCE` | OCI user access token의 실제 `aud` 값 |
|
||||
| `CB_EXTERNAL_IDENTITY_BINDING` | OCI `iss + sub` → Alice/Bob application user 등록 |
|
||||
| AIPF MCP source | OCI OAuth client ID/secret/endpoint로 신규 source 생성 |
|
||||
|
||||
OCI token을 실제로 받은 뒤 audience를 정하는 이유는 client ID, resource scope, Domain 정책에 따라 access token claim이 달라질 수 있기 때문이다. 추측값으로 MCP를 먼저 재시작하면 기존 Keycloak 검증을 불필요하게 중단시킬 수 있다.
|
||||
|
||||
#### 적용 중 확인된 트러블슈팅 기록
|
||||
|
||||
| 증상/오류 | 원인 | 해결/판정 |
|
||||
|---|---|---|
|
||||
| `401 Authorization Required`, endpoint에 `/admin/v1/admin/v1/Apps` | `oci identity-domains ... --endpoint`에 `/admin/v1`까지 넣어 CLI가 경로를 중복 | CLI endpoint에는 Domain base URL만 넣는다. raw request일 때만 target URI에 `/admin/v1/...`를 넣는다. |
|
||||
| `No such option: --header` | `oci raw-request`는 `--header`가 아니라 `--request-headers` 사용 | `--request-headers '{"Content-Type":"application/json"}'`로 호출 |
|
||||
| `Missing required attribute(s): basedOnTemplate.` | OCI App API는 OAuth client 생성 시 template 필수 | `"basedOnTemplate":{"value":"CustomWebAppTemplateId"}` 추가 |
|
||||
| authorization endpoint가 `302`가 아니라 `HTTP 200 OK` | OCI Domain이 redirect 대신 로그인 HTML과 secure session cookie를 반환 | 정상. browser에서 OCI 로그인 화면이 보이면 OAuth preflight 통과로 판정 |
|
||||
| OCI console browser automation 불가 | 현재 작업 환경에 browser binding 없음 | OCI Console 화면 조작이 필요한 Bridge 생성은 RDP/관리자 Console session으로 수행; API로 가능한 OAuth app/MCP 설정은 자동화 계속 |
|
||||
| Windows VM WinRM 5986 `Connection refused` | WinRM HTTPS listener/Windows Firewall/NSG 미구성 | RDP 설치를 사용하거나 WinRM HTTPS를 별도 구성. Bridge 기능의 오류로 해석하지 않음 |
|
||||
| OCI Compute Instance Run Command plugin은 `RUNNING`인데 명령이 계속 `ACCEPTED` / `VISIBLE` | plugin 상태 보고는 가능하지만 Windows agent가 command execution을 수신·실행하지 못함. PowerShell preflight와 단순 `echo` 모두 동일 | Bridge installer 실행 수단으로 사용하지 않는다. Windows의 Oracle Cloud Agent/Run Command service, outbound OCI connectivity, plugin 로그를 RDP에서 점검한 뒤 재시도한다. |
|
||||
| AD Bridge test가 LDAPS certificate 오류 | AD DS 인증서 체인이 Bridge host trust store에 없음 | 사내 CA/AD 인증서를 Bridge host에 신뢰시키고 LDAPS를 유지 |
|
||||
| OCI OAuth login은 성공하지만 MCP `401` | MCP issuer/audience가 Keycloak 값 그대로이거나 OCI `sub` binding 없음 | OCI JWT claim 확인 후 MCP env와 `CB_EXTERNAL_IDENTITY_BINDING`을 함께 교체 |
|
||||
| AIPF source에서 이전 사용자로 로그인 | OCI Domain browser SSO session 유지 | OCI Domain logout 후 source 재연결; AIPF source 저장 token과 browser SSO session을 구분 |
|
||||
|
||||
#### 전환 검증 기준
|
||||
|
||||
| 단계 | 증거 | 성공 기준 |
|
||||
|---|---|---|
|
||||
| AD Bridge 연결 | Bridge 상태 `Connected`, AD 사용자/그룹 동기화 결과 | `dds-alice`, `dds-bob`이 OCI Domain에 존재 |
|
||||
| delegated authentication | OCI Domain의 test delegated authentication | 두 사용자의 AD 비밀번호로 성공 |
|
||||
| OAuth code flow | AIPF가 OCI login → callback → MCP source 연결 완료 | OCI issuer의 access token이 저장됨 |
|
||||
| MCP 검증 | OCI JWT의 signature/issuer/audience 통과 | `iss + sub` mapping 조회 성공 |
|
||||
| DDS 권한 | 같은 `휴가` tool 호출 | Alice 1건, Bob default deny |
|
||||
| 회귀/보안 | Keycloak token, 미매핑 OCI token, 만료 token | DB query 전 거부 |
|
||||
|
||||
### 이 설계가 답하는 질문
|
||||
|
||||
이 PoC는 다음 네 가지를 의도적으로 분리한다.
|
||||
|
||||
| 질문 | 답 | 담당 구성요소 |
|
||||
|---|---|---|
|
||||
| 직원 계정과 비밀번호는 어디에 있는가? | Windows AD DS가 원천이다. | AD DS |
|
||||
| 사용자가 MCP에 로그인했음을 어떻게 증명하는가? | Keycloak이 AD LDAP 인증을 거쳐 OIDC access token(JWT)을 발급한다. | Keycloak |
|
||||
| MCP 서버가 Oracle DB에 접속해 DDS context를 열 자격은 어떻게 얻는가? | OCI Identity Domain의 confidential service client가 database-access token을 발급받는다. | OCI IAM integrated application / credential app |
|
||||
| Alice와 Bob이 서로 다른 데이터만 보게 하는 최종 판단은 누가 하는가? | Oracle Deep Sec이 요청별 local DDS END USER와 DATA GRANT를 적용한다. | Oracle Database |
|
||||
|
||||
즉, **AD 계정으로 로그인한 사용자 토큰**과 **MCP 서버가 DB에 접속하는 서비스 토큰**은 목적과 발급자가 다른 별개의 token이다. 전자는 “누가 요청했는가”를, 후자는 “어떤 애플리케이션이 DB context를 열 수 있는가”를 증명한다. 하나를 다른 하나의 대체물로 쓰지 않는다.
|
||||
|
||||
## 2. 격리 인프라
|
||||
|
||||
| 항목 | 구성 |
|
||||
|---|---|
|
||||
| 네트워크 | `handson-vcn`의 전용 `10.0.2.0/28` public subnet |
|
||||
| Windows VM | `hmm-ad-dss-test-isolated`, Windows Server 2022, 2 OCPU / 16 GB |
|
||||
| 관리 접근 | RDP TCP/3389은 작업자 공인 IP 한 곳에만 NSG로 허용 |
|
||||
| OIDC HTTPS | `https://ad.cloud-handson.com` (Caddy TLS reverse proxy → Keycloak) |
|
||||
| 서브넷 보안 목록 | 인바운드 전부 차단, Windows Update 및 테스트용 아웃바운드만 허용 |
|
||||
| 도메인 | `dds.test` (AD DS forest/domain) |
|
||||
|
||||
이 VM은 테스트 전용이다. 기존 공유 public subnet의 NAT 경로를 변경하지 않으며, 비용 발생 리소스이므로 검증 종료 뒤 중지 또는 삭제를 결정한다.
|
||||
|
||||
## 3. 식별자와 권한 흐름
|
||||
|
||||
```text
|
||||
AD 사용자 (UPN: alice@dds.test, objectGUID)
|
||||
│ LDAP / OIDC bridge
|
||||
▼
|
||||
검증된 Bearer claims
|
||||
iss, aud, exp, sub = 불변 외부 subject
|
||||
│ MCP bearer authenticator
|
||||
▼
|
||||
CB_EXTERNAL_IDENTITY_BINDING
|
||||
issuer + subject -> CB_APP_USER.user_id
|
||||
▼
|
||||
CB_DDS_END_USER_MAP
|
||||
user_id -> DDS_U_<user_id> local END USER
|
||||
▼
|
||||
ORA_END_USER_CONTEXT + DDS DATA GRANT / 권한 함수
|
||||
```
|
||||
|
||||
`sub`는 Keycloak이 발급하는 안정적인 federated-user 식별자다. AD objectGUID는 원천 디렉터리의 감사 식별자로 유지하되, 실제 권한 키는 **검증된 JWT의 `iss + sub`**로 고정한다. UPN은 로그인 화면·감사 표시용으로 보관할 수 있지만 권한 키로 신뢰하지 않는다. `iss + sub` 조합이 유일하지 않거나, 매핑이 없거나, 사용자가 비활성이면 요청은 fail-closed로 거부한다.
|
||||
|
||||
### 전체 요청 흐름
|
||||
|
||||
```text
|
||||
(1) 사용자가 AIPF에서 dds MCP를 연결
|
||||
│ OAuth authorization code flow
|
||||
▼
|
||||
(2) Keycloak 로그인 화면
|
||||
│ AD LDAP bind: dds-alice / dds-bob의 비밀번호 확인
|
||||
▼
|
||||
(3) Keycloak access token 발급
|
||||
│ iss, aud=dds-mcp, exp, sub 포함 / Keycloak signing key로 서명
|
||||
▼
|
||||
(4) AIPF가 MCP 요청에 Bearer access token을 첨부
|
||||
▼
|
||||
(5) MCP
|
||||
│ Keycloak JWKS로 서명·issuer·audience·만료 검증
|
||||
│ CB_EXTERNAL_IDENTITY_BINDING에서 iss+sub 조회
|
||||
▼
|
||||
(6) MCP가 OCI IAM service token을 별도로 획득
|
||||
│ client credentials: DDS_MCP_SERVICE_TEST
|
||||
▼
|
||||
(7) Oracle DB
|
||||
│ service token으로 trusted application identity 확인
|
||||
│ 조회한 DDS_U_n end-user context attach
|
||||
▼
|
||||
(8) Deep Sec
|
||||
│ DDS_U_n의 DATA ROLE/DATA GRANT만 적용하여 SQL 실행
|
||||
▼
|
||||
(9) MCP가 허용된 결과만 AIPF로 반환
|
||||
```
|
||||
|
||||
MCP는 이 흐름의 **정책 집행점**이다. 사용자의 JWT를 검증하지 못하면 5단계에서 멈추고, DB service token이 유효하지 않으면 7단계에서 멈추며, 둘 다 통과해도 해당 DDS END USER의 grant가 없으면 8단계에서 멈춘다. 어느 단계에서도 실패를 우회하여 공유 DB 계정의 광범위한 권한으로 조회해서는 안 된다.
|
||||
|
||||
### 사용자 인증과 DB 접속 신뢰의 분리
|
||||
|
||||
이 PoC에는 서로 다른 두 신뢰 체인이 있다. 둘을 같은 OAuth token으로 혼동하지 않는다.
|
||||
|
||||
```text
|
||||
[업무 사용자 인증]
|
||||
AD user -> Keycloak (AD LDAP 인증) -> Keycloak JWT
|
||||
-> MCP validates iss + sub -> DDS_U_1 / DDS_U_2 선택
|
||||
|
||||
[DB 접속 신뢰]
|
||||
MCP service -> OCI IAM DDS_MCP_SERVICE_TEST (client credentials)
|
||||
-> database-access token -> Oracle DB
|
||||
-> 선택된 local DDS END USER context attach
|
||||
```
|
||||
|
||||
| 역할 | 현재 담당 | 하는 일 |
|
||||
|---|---|---|
|
||||
| AD 사용자 인증 | Keycloak | AD LDAP의 계정·비밀번호를 확인하고 Keycloak JWT를 발급 |
|
||||
| 업무 사용자 식별 | MCP | 검증된 Keycloak `iss + sub`를 HMM application user와 local DDS END USER에 매핑 |
|
||||
| DB 접속 애플리케이션 신뢰 | OCI IAM credential app | MCP service가 database-access token을 받아 Oracle DB에 신뢰된 application임을 증명 |
|
||||
| 최종 데이터 권한 | Oracle Deep Sec | attach된 local DDS END USER의 DATA ROLE과 DATA GRANT로 행·열을 제한 |
|
||||
|
||||
따라서 OCI IAM credential app은 현재 AD 사용자를 직접 로그인시키지 않는다. OCI IAM은 MCP service의 database-access token 발급자이며, Oracle DB가 해당 service client를 application identity로 신뢰하게 한다. AD 사용자가 어떤 DDS END USER가 되는지는 MCP가 결정한다.
|
||||
|
||||
향후 OCI IAM을 사용자 인증의 중심으로 바꾸려면 Keycloak을 OCI IAM의 외부 IdP(OIDC 또는 SAML)로 federation하고, AIPF/MCP가 OCI IAM user token을 받도록 변경한다. 그 경우 Oracle DB도 OCI IAM user token의 issuer·group claim을 직접 검증할 수 있다. 현재 PoC의 local DDS END USER 매핑과는 별도의 확장 경로다.
|
||||
|
||||
### OCI Identity Domain integrated application을 쓰는 이유와 역할
|
||||
|
||||
여기서 말하는 OCI Domain integrated application은 `DDS_ORACLE_DB_TEST` database resource application이다. 이를 사용자용 웹 로그인 앱으로 오해하면 안 된다. 이 앱은 **Oracle Autonomous Database가 신뢰할 OAuth audience와 scope를 OCI Identity Domain에 선언하는 등록물**이다.
|
||||
|
||||
일반 OAuth access token은 “어느 resource server를 위한 token인지”가 불명확하면 DB가 받아들여서는 안 된다. integrated application은 DB용 resource identity를 만들고, `DB_ACCESS_SCOPE` 같은 전용 scope를 발급 정책에 묶는다. 그러면 DB는 다음 세 가지가 일치할 때만 MCP의 service token을 받아들인다.
|
||||
|
||||
| DB가 확인하는 값 | integrated application에서 정하는 값 | 이 PoC의 의미 |
|
||||
|---|---|---|
|
||||
| resource application | `DDS_ORACLE_DB_TEST` | 이 token의 수신자가 DDS 대상 Oracle DB임을 식별 |
|
||||
| scope | `DB_ACCESS_SCOPE` | DB context 접근이라는 최소 권한을 명시 |
|
||||
| issuer | OCI Identity Domain URL | token을 발급하고 서명키를 제공하는 신뢰 경계 |
|
||||
| OAuth client ID | `DDS_MCP_SERVICE_TEST` | token을 요청한 MCP service를 식별 |
|
||||
|
||||
`DDS_MCP_SERVICE_TEST`는 integrated application 자체가 아니라, 그 resource/scope를 요청할 수 있도록 허가된 **confidential service client**다. client secret을 가진 백엔드 MCP만 client credentials flow로 token을 발급받는다. 브라우저·AIPF·AD 사용자는 이 secret이나 service token을 보거나 보관하지 않는다.
|
||||
|
||||
```text
|
||||
OCI Identity Domain
|
||||
|
||||
DDS_ORACLE_DB_TEST DDS_MCP_SERVICE_TEST
|
||||
(resource / integrated app) (confidential OAuth client)
|
||||
┌───────────────────────┐ ┌─────────────────────────┐
|
||||
│ audience: Oracle DB │<--scope--│ client credentials only │
|
||||
│ scope: DB_ACCESS_SCOPE│ │ secret: MCP host only │
|
||||
└──────────┬────────────┘ └───────────┬─────────────┘
|
||||
│ database-access token │ token request
|
||||
└────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
Autonomous DB application identity
|
||||
```
|
||||
|
||||
이 구조를 쓰는 이유는 DB password를 MCP에 장기 보관하거나, 모든 사용자에게 DB 로그인 권한을 주지 않기 위해서다. service client는 DB context를 여는 최소 권한만 보유하고, 사람별 데이터 권한은 local DDS END USER에 남긴다. 서비스 client secret이 노출되더라도 해당 client에 부여하지 않은 데이터 권한이 자동으로 생기는 구조가 아니다. 다만 token 발급과 DB context 생성 자체를 악용할 수 있으므로 secret은 즉시 회전하고, 이 client에는 불필요한 OCI 권한을 부여하지 않는다.
|
||||
|
||||
### OCI IAM과 Keycloak을 함께 쓰는 이유
|
||||
|
||||
현재 AD DS는 LDAP/Kerberos 디렉터리이지 인터넷 서비스가 직접 검증할 OAuth JWT issuer는 아니다. Keycloak은 AD LDAP과 OIDC 사이의 번역 계층이다. 반면 OCI IAM integrated application은 Oracle DB가 지원하는 database-access token contract를 제공한다.
|
||||
|
||||
| 경계 | 입력 | 출력 | 선택 이유 |
|
||||
|---|---|---|---|
|
||||
| AD DS → Keycloak | AD 사용자명/비밀번호, LDAP 사용자·그룹 | Keycloak OIDC JWT | AD를 계정 원천으로 유지하면서 표준 OAuth/OIDC를 제공 |
|
||||
| Keycloak → MCP | Keycloak JWT/JWKS | 검증된 `iss + sub` | MCP가 사용자 identity를 안전하게 해석 |
|
||||
| MCP → OCI IAM | service client ID/secret | DB 전용 access token | DB가 신뢰할 service identity 증명 |
|
||||
| OCI IAM → Oracle DB | database-access token | application identity | DB password 없이 DB context 접근을 제한 |
|
||||
| Oracle DB → DDS | local END USER | 필터된 query 결과 | 데이터 권한을 DB 내부에서 강제 |
|
||||
|
||||
따라서 “OCI Domain credential app이 AD를 신뢰한다”는 표현은 현재 PoC에는 정확하지 않다. 현재는 **Keycloak이 AD를 신뢰해 사용자 인증을 수행**하고, **Oracle DB가 OCI IAM을 신뢰해 MCP service를 인증**한다. 두 체인은 MCP 안에서 만나며, MCP가 Keycloak token의 subject를 local DDS END USER로 결정한다.
|
||||
|
||||
## 4. 구현 단계
|
||||
|
||||
1. Windows Server에 AD DS를 설치하고 `dds.test` forest를 생성한다.
|
||||
2. 테스트 사용자 `dds-alice`, `dds-bob`와 권한 그룹을 만들고, LDAP 조회와 인증을 확인한다.
|
||||
3. AD LDAP과 연동한 OIDC bridge(예: Keycloak)를 별도 서비스로 구성한다. bridge가 내는 JWT의 `iss`, `aud`, `exp`, JWKS 서명을 MCP가 검증한다.
|
||||
4. `issuer + sub`에서 `CB_APP_USER` 및 `CB_DDS_END_USER_MAP`을 해석하도록 백오피스/DB 매핑을 추가한다.
|
||||
5. alice/bob의 서로 다른 `DDS_U_*` context에서 동일 MCP tool 호출 결과가 권한에 따라 달라지는지 검증한다.
|
||||
6. 매핑 누락, 만료 토큰, 다른 issuer/audience, 비활성 계정은 모두 거부되는 regression을 추가한다.
|
||||
|
||||
## 4.1 현재 테스트 bridge
|
||||
|
||||
`database/adb/47_dds_ad_identity_test_setup.sql`은 HMM DB의 기존 업무 사용자 원천을 변경하지 않는다. 스크립트가 만든 `CB_EXTERNAL_IDENTITY_BINDING`에는 최종 OIDC issuer와 Keycloak이 실제로 발급한 subject만 보관한다.
|
||||
|
||||
| AD 사용자 | OIDC issuer | JWT `sub` | HMM application user | DDS END USER |
|
||||
|---|---|---|---:|---|
|
||||
| `dds-alice` | `https://ad.cloud-handson.com/realms/dds-test` | `11cf09c9-4713-4145-85cd-e3397d4a2405` | 1 | `DDS_U_1` |
|
||||
| `dds-bob` | `https://ad.cloud-handson.com/realms/dds-test` | `d9610e18-a327-4dda-9496-69e5a2067460` | 2 | `DDS_U_2` |
|
||||
|
||||
`dds-mcp` client는 access token audience에 `dds-mcp`를 포함한다. MCP는 Keycloak JWKS에서 JWT 서명과 `iss`, `aud`, 만료 시간을 검증한 뒤에만 위 매핑을 조회한다. 실제 `/dds/mcp/messages` 초기화 요청에 Alice JWT를 넣어 성공 응답을 확인했다.
|
||||
|
||||
초기 게시 단계에서는 END USER와 DATA ROLE만 만들고 default deny로 시작한다. 현재 테스트에서는 Alice에만 vector view SELECT data grant를 추가했고 Bob은 grant 없이 유지한다.
|
||||
|
||||
### Keycloak 구성에서 중요한 값
|
||||
|
||||
Keycloak realm `dds-test`은 AD LDAP user federation을 사용한다. 로그인 화면에서 입력한 `dds-alice` 또는 `dds-bob`의 비밀번호 검증은 AD DS가 담당하며, Keycloak은 성공한 LDAP 사용자의 immutable identity를 자신의 `sub`로 유지해 JWT에 넣는다. AD 비밀번호나 LDAP bind credential은 MCP와 AIPF에 전달되지 않는다.
|
||||
|
||||
| Keycloak 항목 | 값/정책 | 필요한 이유 |
|
||||
|---|---|---|
|
||||
| Realm issuer | `https://ad.cloud-handson.com/realms/dds-test` | MCP의 허용 issuer와 identity binding의 namespace |
|
||||
| MCP audience | `dds-mcp` | 다른 Keycloak client용 token의 재사용 방지 |
|
||||
| AIPF confidential client | `aipf-dds-mcp` | AIPF OAuth callback과 token exchange 수행 |
|
||||
| MCP resource client | `dds-mcp` | access token audience 검증 대상 |
|
||||
| Redirect URI | AIPF callback 두 경로와 wildcard 등록 | authorization code를 허용된 AIPF에만 반환 |
|
||||
| PKCE | AIPF client에서 미사용 | 현재 AIPF가 `code_challenge_method`를 보내지 않기 때문; 향후 AIPF 지원 시 S256으로 전환 |
|
||||
| Direct grant | 테스트 client에서만 제한적으로 사용 | CLI 검증용; 운영 browser client에는 사용하지 않음 |
|
||||
|
||||
JWT 검증은 서명만 확인하는 것으로 충분하지 않다. MCP는 최소한 다음을 모두 확인해야 한다.
|
||||
|
||||
1. `alg`가 허용된 비대칭 서명 알고리즘인지 확인하고, Keycloak JWKS의 해당 `kid`로 signature를 검증한다.
|
||||
2. `iss`가 realm issuer와 정확히 같은지 확인한다. URL의 realm·host가 다른 token은 거부한다.
|
||||
3. `aud`에 `dds-mcp`가 포함됐는지 확인한다.
|
||||
4. `exp`, `nbf`, `iat` 및 허용 clock skew를 검사한다.
|
||||
5. 검증된 `iss + sub`로만 `CB_EXTERNAL_IDENTITY_BINDING`을 조회한다. browser가 표시한 email, username, group 문자열만으로 매핑하지 않는다.
|
||||
|
||||
Keycloak signing key rotation 시 MCP의 JWKS cache가 새 `kid`를 다시 조회할 수 있어야 한다. issuer나 realm을 바꾸면 binding table의 issuer 값과 MCP allow-list도 함께 변경해야 한다.
|
||||
|
||||
### 테스트 Keycloak 사용자 비밀번호를 얻는 방법
|
||||
|
||||
**실제 로그인 인증 원천은 Windows AD DS다.** `dds-alice`와 `dds-bob`은 Keycloak에 로컬로 만든 계정이 아니라 AD DS의 테스트 사용자다. AIPF가 Keycloak 로그인 화면으로 이동하면 사용자는 AD 사용자명과 AD 비밀번호를 입력하고, Keycloak은 LDAP을 통해 AD에 비밀번호를 확인한다. AD 인증이 성공할 때에만 Keycloak이 OIDC JWT를 발급한다.
|
||||
|
||||
```text
|
||||
사용자: dds-alice + AD 비밀번호 입력
|
||||
│
|
||||
▼
|
||||
Keycloak ── LDAP 인증 요청 ──► Windows AD DS
|
||||
│ │
|
||||
└── 인증 성공 ◄─────┘
|
||||
│
|
||||
▼
|
||||
Keycloak OIDC access token 발급
|
||||
```
|
||||
|
||||
`.runtime/dds-ad-test-users.env`는 인증 서버나 Keycloak 설정이 아니다. 테스트 중 AD 비밀번호를 안전하게 다시 입력할 수 있도록 **현재 AD에 설정된 테스트 비밀번호를 로컬에서 참고하는 git-ignore 파일**일 뿐이다. AD에서 비밀번호를 변경하면 실제 로그인에는 새 AD 비밀번호가 즉시 적용되며, 이 파일은 참고값으로만 함께 갱신한다. 이 비밀번호는 OAuth client secret이나 OCI IAM service client secret과 전혀 다른 값이다.
|
||||
|
||||
실제 값은 저장소·문서·채팅에 기록하지 않는다. 현재 작업 환경에서는 git-ignore된 권한 제한 파일 `.runtime/dds-ad-test-users.env`에 보관한다. 다음 명령은 비밀번호를 터미널에 표시하지 않고 macOS 클립보드에 복사한다.
|
||||
|
||||
```bash
|
||||
# dds-alice 비밀번호 복사
|
||||
sed -n 's/^DDS_ALICE_PASSWORD=//p' .runtime/dds-ad-test-users.env | pbcopy
|
||||
|
||||
# dds-bob 비밀번호 복사
|
||||
sed -n 's/^DDS_BOB_PASSWORD=//p' .runtime/dds-ad-test-users.env | pbcopy
|
||||
```
|
||||
|
||||
명령 출력이 없는 것이 정상이다. 원하는 사용자 항목을 실행한 다음 Keycloak 로그인 화면의 password 칸에 `⌘V`로 붙여넣는다. 로그인 ID는 각각 `dds-alice`, `dds-bob`이며, 도메인 표기가 필요한 Windows/LDAP 화면에서는 `DDS\\dds-alice`, `DDS\\dds-bob`을 사용한다. `pbcopy`가 올바른 명령이며 `pbcop`는 오타다.
|
||||
|
||||
파일이 없거나 비밀번호가 맞지 않으면 값 추측이나 문서 검색을 하지 않는다. AD 관리자에게 test-user password reset을 요청하고, reset 후 이 권한 제한 파일만 갱신한다. user password reset은 AIPF OAuth client secret이나 OCI IAM service client secret rotation을 의미하지 않는다.
|
||||
|
||||
## 4.2 AIPF MCP 등록 값
|
||||
|
||||
AIPF의 **Edit MCP server** 화면에서 다음 값으로 등록한다. AIPF는 confidential OAuth client를 요구하므로, 일반 테스트용 public client `dds-mcp`가 아니라 AIPF 전용 client `aipf-dds-mcp`를 사용한다.
|
||||
|
||||
| AIPF 항목 | 입력값 |
|
||||
|---|---|
|
||||
| Server name | `alice-dds` (Bob 검증 때는 `bob-dds`처럼 별도 등록) |
|
||||
| Server URL | `https://hmm-backoffice.cloud-handson.com/mcp/dds/sse` |
|
||||
| Authentication mode | `OAuth` |
|
||||
| Redirect callback URL | AIPF 표시값 `https://aipf.cloud-handson.com/agentFactory/v1/tools/mcp/callback` — 입력하지 않는 읽기 전용 값 |
|
||||
| OAuth client ID | `aipf-dds-mcp` |
|
||||
| OAuth client secret | 운영자 보관 secret. 저장소·문서·대화에 기록하지 않는다. 현재 작업 환경에서는 `.runtime/aipf-dds-mcp-client.env`의 `OAUTH_CLIENT_SECRET` 값을 사용한다. |
|
||||
| Authorization URL | `https://ad.cloud-handson.com/realms/dds-test/protocol/openid-connect/auth` |
|
||||
| Token URL | `https://ad.cloud-handson.com/realms/dds-test/protocol/openid-connect/token` |
|
||||
| Refresh URL | `https://ad.cloud-handson.com/realms/dds-test/protocol/openid-connect/token` |
|
||||
| Scopes | `openid profile email` |
|
||||
|
||||
### OAuth client secret을 얻는 방법
|
||||
|
||||
여기서 필요한 secret은 AD 사용자 비밀번호가 아니라 Keycloak의 `aipf-dds-mcp` OAuth client secret이다. secret은 저장소에 커밋하거나 문서·대화에 적지 않는다. 현재 작업 환경에서는 권한 제한 파일에 보관하며, 다음 명령으로 **값을 화면에 표시하지 않고** macOS 클립보드에 복사한다.
|
||||
|
||||
```bash
|
||||
sed -n 's/^OAUTH_CLIENT_SECRET=//p' .runtime/aipf-dds-mcp-client.env | pbcopy
|
||||
```
|
||||
|
||||
명령 출력이 없는 것이 정상이다. 이후 AIPF의 **OAuth client secret** 입력칸에 `⌘V`로 붙여넣고 저장한다. 복사 명령은 `pbcopy`이며 `pbcop`가 아니다. 파일의 secret 값은 Keycloak에서 OAuth client를 재생성하거나 rotation한 경우에만 다시 동기화한다.
|
||||
|
||||
### AIPF callback 호환 보정
|
||||
|
||||
현재 AIPF는 화면에 표시하는 callback과 달리 OAuth authorization request에는 `/agentFactory`가 빠진 `https://aipf.cloud-handson.com/v1/tools/mcp/callback`을 보낸다. AIPF Nginx는 이 경로를 같은 origin의 실제 callback으로 302 전환하도록 구성했다.
|
||||
|
||||
```text
|
||||
/v1/tools/mcp/callback
|
||||
-> /agentFactory/v1/tools/mcp/callback
|
||||
```
|
||||
|
||||
이 전환은 OAuth `code`와 `state`를 보존하고 브라우저가 `/agentFactory` 범위의 AIPF 세션 쿠키를 다시 전송하게 한다. AIPF의 OAuth callback 생성 로직이 수정되면 이 Nginx 보정은 제거할 수 있다.
|
||||
|
||||
### AIPF 로그인 상태와 MCP 등록을 구분할 것
|
||||
|
||||
AIPF의 MCP 등록 정보와 Keycloak의 브라우저 SSO 세션은 서로 다르다.
|
||||
|
||||
| 상태 | 보관 위치 | 영향 |
|
||||
|---|---|---|
|
||||
| MCP OAuth client ID/secret, 연결 설정 | AIPF의 MCP source 설정 | 최초 OAuth 연결 및 refresh token 교환에 사용 |
|
||||
| Keycloak SSO 로그인 세션 | 브라우저의 `ad.cloud-handson.com` cookie | 다음 OAuth 연결 시 이전 사용자로 자동 로그인될 수 있음 |
|
||||
| AIPF가 저장한 MCP token/refresh token | AIPF backend source별 저장소 | 등록한 MCP source가 이후 tool 호출할 때 사용 |
|
||||
|
||||
그러므로 Alice에서 Bob을 시험할 때는 source를 `bob-dds`로 새로 만들거나 기존 연결을 끊고, Keycloak logout을 먼저 수행한다. 같은 browser session에서 바로 다시 연결하면 AIPF 설정을 Bob으로 바꿔도 Keycloak SSO가 Alice를 다시 인증할 수 있다. Keycloak logout endpoint는 다음과 같다.
|
||||
|
||||
```text
|
||||
https://ad.cloud-handson.com/realms/dds-test/protocol/openid-connect/logout
|
||||
```
|
||||
|
||||
새 AIPF source에는 OAuth client ID와 secret을 다시 입력한다. source 간에 인증정보가 자동 상속된다고 가정하지 않는다.
|
||||
|
||||
## 4.3 테스트 시나리오
|
||||
|
||||
### A. Alice 인증과 MCP 연결
|
||||
|
||||
1. AIPF에서 위 값으로 `alice-dds`를 저장하고 연결한다.
|
||||
2. Keycloak 로그인 화면에서 AD 사용자 `dds-alice`로 로그인한다. 도메인 표기가 필요하면 `DDS\\dds-alice`를 사용한다.
|
||||
3. AIPF가 callback으로 돌아오면 `alice-dds` MCP 연결이 완료된다.
|
||||
4. AIPF Agent 대화에서 다음 요청을 실행한다.
|
||||
|
||||
```text
|
||||
dds_vector_search 도구를 사용해서 "휴가"를 검색해줘.
|
||||
embeddingMode는 DEMO, limit은 10으로 해줘.
|
||||
```
|
||||
|
||||
5. MCP는 Keycloak access token의 검증된 `iss + sub`를 Alice의 application user와 `DDS_U_1`에 매핑한 뒤 `dds_vector_search`를 호출한다.
|
||||
|
||||
### B. Bob 권한 비교
|
||||
|
||||
1. AIPF OAuth 연결을 끊거나 새 MCP 등록 `bob-dds`를 만든다.
|
||||
2. 같은 OAuth 설정으로 연결한 뒤 AD 사용자 `dds-bob`으로 로그인한다.
|
||||
3. Alice와 동일한 검색 요청을 실행한다.
|
||||
4. DDS data grant 구성 후 기대 결과는 다음과 같다.
|
||||
|
||||
| 사용자 | JWT subject 매핑 | 기대 결과 |
|
||||
|---|---|---|
|
||||
| `dds-alice` | application user `1` → `DDS_U_1` | 허용된 지식 행만 반환 |
|
||||
| `dds-bob` | application user `2` → `DDS_U_2` | 빈 결과 또는 DDS 권한 거부 |
|
||||
|
||||
### C. 판정 기준과 현 상태
|
||||
|
||||
| 확인 항목 | 판정 방법 | 현재 상태 |
|
||||
|---|---|---|
|
||||
| OAuth 로그인 | AIPF가 Keycloak 로그인 후 MCP 등록 화면으로 복귀 | 확인 완료 |
|
||||
| JWT 검증/매핑 | `tools/list` 또는 `dds_vector_search`가 Bearer 토큰 검증을 통과 | 확인 완료 |
|
||||
| Alice/Bob 데이터 차이 | 같은 `dds_vector_search` 호출에서 반환 행이 다름 | 확인 완료 — Alice 1건 반환, Bob default deny |
|
||||
| 미매핑 토큰 거부 | 매핑 없는 `iss + sub`의 MCP 호출이 `AUTHORIZATION_DENIED` | 구현 완료, 회귀 검증 대기 |
|
||||
|
||||
`dds_vector_search`는 현재 유일한 DDS MCP 도구이며 입력값은 `query`(필수), `limit`(1~100), `embeddingMode`(`DEMO` 또는 `AI`)다. service identity와 Alice 허용/Bob 거부 DDS grant를 반영해 권한 차이까지 검증했다.
|
||||
|
||||
## 4.4 OCI IAM database-access token 구성
|
||||
|
||||
Keycloak access token은 MCP의 업무 사용자 식별과 `iss + sub` 매핑에만 사용한다. Oracle Deep Sec context를 열 때는 별도의 OCI IAM database-access token이 필요하다. 이 토큰은 `DDS_MCP_SERVICE_TEST` confidential client가 client credentials flow로 받고, DB는 해당 client ID를 application identity로 신뢰한다.
|
||||
|
||||
```text
|
||||
AD user -> Keycloak token -> MCP user mapping -> local DDS END USER
|
||||
\
|
||||
OCI IAM DDS_MCP_SERVICE_TEST -- database-access token --> Oracle Deep Sec context
|
||||
```
|
||||
|
||||
구성 순서는 OCI IAM database resource(`DDS_ORACLE_DB_TEST`)와 scope(`DB_ACCESS_SCOPE`) 생성, OCI IAM service client 생성, Autonomous DB의 OCI IAM identity provider/credential 등록, 그리고 `CREATE APPLICATION IDENTITY ... MAPPED TO 'IAM_OAUTH_CLIENT_ID=...'` 순서다. 이 단계는 Autonomous DB의 외부 인증 구성을 변경할 수 있으므로 기존 설정을 먼저 조회하고 Redmine에 기록한다.
|
||||
|
||||
### 실제 구성 절차와 신뢰 등록 방향
|
||||
|
||||
다음 순서는 “누가 누구를 신뢰하도록 등록하는가”를 기준으로 작성했다. secret, client ID, application ID는 환경별 값이므로 이 문서에 넣지 않고 권한 제한 환경 파일 또는 OCI console에서 관리한다.
|
||||
|
||||
1. OCI Identity Domain에서 database resource/integrated application `DDS_ORACLE_DB_TEST`를 만들고 `DB_ACCESS_SCOPE`를 정의한다. 이것이 DB가 받아들일 audience와 scope의 계약이다.
|
||||
2. 같은 Domain에서 confidential client `DDS_MCP_SERVICE_TEST`를 만든다. grant type은 `client_credentials`만 허용하고, 1단계의 DB scope만 허용한다. 발급된 client secret은 MCP host의 mode 600 환경 파일에만 저장한다.
|
||||
3. Autonomous DB에 OCI IAM external authentication을 활성화하고, Domain URL 및 database resource application ID를 등록한다. DB의 issuer URL은 token `iss`와 정규형까지 일치해야 한다. 이 환경에서는 HTTPS `:443`을 포함한다.
|
||||
4. DB에 OCI IAM signing-key credential을 만들고, `DDS_MCP_SERVICE_TEST`의 OAuth client ID를 DB application identity에 매핑한다. 이 단계로 DB는 “이 client credentials로 발급된 DB token을 가진 서비스”를 신뢰한다.
|
||||
5. HMM MCP runtime에 service client ID, secret, token endpoint, scope, resource 대상 view를 주입하고 서비스 계정을 재시작한다. 사용자 access token이나 AD 비밀번호를 이 파일에 넣지 않는다.
|
||||
6. 별도로 Keycloak `iss + sub` → `CB_APP_USER` → `CB_DDS_END_USER_MAP`을 등록한다. `DDS_U_1_ROLE` 같은 local role에 대상 객체 DATA GRANT를 필요한 사용자에게만 부여한다.
|
||||
|
||||
신뢰의 방향은 아래와 같다.
|
||||
|
||||
```text
|
||||
AD DS ──(LDAP credential 확인)──► Keycloak
|
||||
Keycloak ──(signed user JWT)────► MCP
|
||||
MCP ──(client credentials)──────► OCI Identity Domain
|
||||
OCI Identity Domain ──(signed DB token)──► Oracle DB
|
||||
Oracle DB ──(DDS grant 평가)────► 데이터
|
||||
```
|
||||
|
||||
Oracle DB는 AD DS나 Keycloak을 직접 신뢰하도록 등록되어 있지 않다. 반대로 OCI IAM integrated application도 AD 사용자 credential을 검증하지 않는다. MCP가 두 신뢰 체인의 검증 결과를 결합하는 위치다.
|
||||
|
||||
### MCP 런타임에서 token을 사용하는 방식
|
||||
|
||||
MCP 요청을 처리할 때 서비스는 두 token을 다음 순서로 취급한다.
|
||||
|
||||
| 순서 | token | MCP가 하는 일 | 실패하면 |
|
||||
|---:|---|---|---|
|
||||
| 1 | Keycloak user access token | HTTP `Authorization: Bearer`에서 추출, JWKS 검증, `iss + sub` binding 해석 | `401` 또는 `AUTHORIZATION_DENIED`; DB에 접속하지 않음 |
|
||||
| 2 | OCI IAM database-access token | server-side client credentials로 얻어 DB connection/context attach에 사용 | DDS context 불가; 사용자 token으로 대체하지 않음 |
|
||||
| 3 | 없음(내부 context) | `DDS_U_n`의 data role/data grant로 target view를 query | Oracle default deny; 결과 반환 안 함 |
|
||||
|
||||
MCP endpoint는 `https://hmm-backoffice.cloud-handson.com/mcp/dds/sse`이며, SSE transport의 message endpoint는 `https://hmm-backoffice.cloud-handson.com/mcp/dds/messages`다. browser 주소창으로 SSE URL을 여는 것은 OAuth 로그인 페이지가 아니라 event stream 연결 시도이므로 유효한 동작 검증 방법이 아니다. AIPF OAuth 등록 또는 Bearer token을 포함한 MCP client로 접속해야 한다.
|
||||
|
||||
### 적용 결과와 검증
|
||||
|
||||
| 구성 요소 | 적용값 | 상태 |
|
||||
|---|---|---|
|
||||
| OCI IAM database resource | `DDS_ORACLE_DB_TEST` / `DB_ACCESS_SCOPE` | 적용 완료 |
|
||||
| OCI IAM service client | `DDS_MCP_SERVICE_TEST`, client credentials만 허용 | 적용 완료 |
|
||||
| Autonomous DB identity provider | `OCI_IAM`, database resource app ID와 OCI IAM domain URL 등록 | 적용 완료 |
|
||||
| DB signing-key credential | `OCI_IAM_DOMAIN_DB_CRED$` | 적용 완료 |
|
||||
| DB application identity | `DDS_MCP_SERVICE_TEST` → OCI IAM service client ID | 적용 완료 |
|
||||
| HMM DDS MCP runtime | client ID·secret·scope를 권한 제한 환경 파일로 로드 | 적용 완료 |
|
||||
| Alice data grant | `DDS_U_1_ROLE` → `CB_VECTOR_SEARCH_DOCUMENTS` SELECT | 적용 완료 |
|
||||
| Bob data grant | 없음 | default deny |
|
||||
|
||||
database-access token은 `resource_app_id`, `tenant_iss`, scope가 DB identity provider 등록과 모두 일치해야 한다. OCI IAM domain URL은 token의 issuer와 같은 정규형(`:443` 포함)을 사용했다. 포트가 빠진 URL로 등록하면 Oracle이 `ORA-52602`(invalid database access token)으로 context 사용을 거부한다.
|
||||
|
||||
2026-08-04 검증 결과는 다음과 같다. 동일한 `dds_vector_search` 호출에서 Alice는 DDS context attach 후 query가 성공했고, Bob은 data grant가 없어 보호 객체 조회가 거부됐다. 초기에는 HMM knowledge chunk 데이터가 없어 Alice의 성공 응답 행 수가 `0`이었으나, 이후 비교 가능한 테스트 문서를 추가하여 Alice의 1건 반환까지 재검증했다.
|
||||
|
||||
이후 권한 차이를 눈으로 확인할 수 있도록 `DDS_AD_ALICE_LEAVE_001` 테스트 문서와 `DDS_AD_TEST` 태그를 HMM knowledge 원천에 추가했다. 같은 `휴가` 검색에서 Alice는 이 문서 1건을 반환하고 Bob은 `ORA-00942` 기반 default deny로 거부되는 것을 확인했다.
|
||||
|
||||
### AIPF 화면에서의 권한 차이 해석
|
||||
|
||||
동일한 AIPF Agent 요청을 Alice와 Bob으로 실행한다.
|
||||
|
||||
```text
|
||||
dds_vector_search 도구를 사용해서 "휴가"를 검색해줘.
|
||||
embeddingMode는 DEMO, limit은 10으로 해줘.
|
||||
```
|
||||
|
||||
| 로그인 사용자 | AIPF에서 보이는 결과 | DB 측 실제 의미 | 판정 |
|
||||
|---|---|---|---|
|
||||
| `dds-alice` | `휴가 정책 - Alice 전용 테스트` 1건 반환 | Keycloak `sub` → `DDS_U_1`, `DDS_U_1_ROLE`의 SELECT DATA GRANT가 `CB_VECTOR_SEARCH_DOCUMENTS`에 적용 | 허용 |
|
||||
| `dds-bob` | “검색에 실패했습니다”, “DDS 보호 객체를 조회할 수 없습니다” | Keycloak `sub` → `DDS_U_2`, 해당 role에 DATA GRANT가 없어 Oracle이 `ORA-00942`로 보호 객체를 숨김 | default deny / 정상 차단 |
|
||||
|
||||
따라서 Bob의 AIPF 화면 문구는 시스템 장애가 아니라 의도한 보안 결과다. 현재 MCP 응답은 SQL 오류를 외부에 노출하지 않기 위해 일반 문구로 변환한다. 운영 UI에서는 이를 “접근 권한이 없습니다”로 표시하도록 개선할 수 있지만, PoC의 권한 검증 자체는 Alice 허용·Bob 거부로 완료됐다.
|
||||
|
||||
## 5. 운영 보안 기준과 장애 구분
|
||||
|
||||
### secret과 token의 보관 원칙
|
||||
|
||||
| 값 | 소유자 | 허용 위치 | 금지 위치 |
|
||||
|---|---|---|---|
|
||||
| AD 사용자 비밀번호 | 사용자/AD | AD에서 hash로 관리, 사용자가 Keycloak login form에만 입력 | MCP 설정, AIPF secret, Git, 문서 |
|
||||
| Keycloak AIPF client secret | AIPF OAuth client | 권한 제한 secret store 또는 `.runtime/aipf-dds-mcp-client.env` | Git, Redmine 본문, 채팅 |
|
||||
| OCI IAM service client secret | MCP backend | HMM host의 mode 600 환경 파일/secret manager | AIPF browser, Java source, Git |
|
||||
| Keycloak user access token | AIPF/MCP 요청 경로 | AIPF의 보호된 token 저장소, HTTPS request header | URL query, application log |
|
||||
| OCI IAM DB service token | MCP process memory | token endpoint 응답 및 DB context attach | browser, client log, source code |
|
||||
|
||||
secret rotation 시에는 Keycloak 또는 OCI IAM에서 새 secret을 만들고, 해당 runtime secret store만 갱신한 뒤 서비스를 재시작한다. 이전 secret의 폐기는 새 token 발급과 MCP query를 확인한 후 수행한다. secret의 실제 값은 로그·shell history·스크린샷에도 남기지 않는다.
|
||||
|
||||
### default deny가 정상인 경우와 장애인 경우
|
||||
|
||||
| 관측 결과 | 가능한 원인 | 기대 처리/조치 |
|
||||
|---|---|---|
|
||||
| 이전 Alice로 자동 로그인 | Keycloak SSO cookie가 남아 있음 | logout 후 Bob으로 다시 인증 |
|
||||
| `401` 또는 tools discovery 실패 | Bearer token 없음/만료, issuer·audience 검증 실패, AIPF source OAuth 설정 누락 | AIPF OAuth 설정과 Keycloak token claim 확인 |
|
||||
| `invalid_request: Missing parameter: code_challenge_method` | Keycloak client에 PKCE 강제인데 AIPF가 PKCE를 보내지 않음 | 현재 AIPF client의 PKCE 정책을 호환 설정으로 조정; AIPF 지원 후 S256 전환 |
|
||||
| `unauthorized_client` / invalid client credentials | AIPF에 잘못된 Keycloak client secret 저장 | 안전한 runtime 파일에서 secret을 다시 복사하고 source 재연결 |
|
||||
| `DDS_CONTEXT_UNAVAILABLE` | OCI IAM client/scope/token endpoint 또는 DB external auth 구성 누락 | service client scope, DB application identity, domain issuer URL 점검 |
|
||||
| Oracle `ORA-52602` | database-access token issuer/resource/scope와 DB 등록값 불일치 | Domain URL 정규형(이 환경은 `:443` 포함), resource app ID와 scope 점검 |
|
||||
| Alice는 결과, Bob은 “DDS 보호 객체” 오류 | Bob에 DATA GRANT 없음 | 의도한 default deny. 정책상 필요한 경우에만 최소 grant 추가 |
|
||||
| Alice도 Bob도 모두 결과 없음 | source data 부재, vector/embedding 조건, 공통 service token 문제 | 데이터 존재 여부와 DDS context attach를 분리해 점검 |
|
||||
|
||||
권한 거부와 인프라 장애를 구분하기 위해 MCP 내부 log에는 SQLState/Oracle error code를 남길 수 있으나, 외부 MCP 응답에는 table명·SQL·DB credential 정보를 노출하지 않는다. 감사 로그에는 요청 시각, correlation ID, token의 `iss + sub` hash 또는 내부 user ID, 선택된 DDS END USER, tool명, allow/deny 결과를 남긴다.
|
||||
|
||||
### 최소 권한 운영 원칙
|
||||
|
||||
1. `DDS_MCP_SERVICE_TEST`에는 database-access scope 외의 OCI 권한을 부여하지 않는다.
|
||||
2. DB application identity는 MCP runtime 전용이며, 개인 사용자나 AIPF browser가 직접 사용하지 않는다.
|
||||
3. local DDS END USER에는 필요한 DATA ROLE만 붙이고, 권한은 object/row/column 단위로 좁힌다. 새 사용자는 grant 없이 생성하는 default deny를 기본으로 한다.
|
||||
4. `CB_EXTERNAL_IDENTITY_BINDING` 변경은 관리자만 수행하고 issuer와 immutable subject를 audit한다. UPN/email 변경만으로 기존 권한이 다른 계정에 이전되지 않아야 한다.
|
||||
5. HTTPS는 Keycloak, AIPF, MCP 모두에서 강제하고, JWKS·token endpoint 호출의 TLS 검증을 끄지 않는다.
|
||||
6. AD DS VM의 RDP와 LDAP 접근은 관리망/허용 IP로 제한한다. public LDAP/LDAPS를 인터넷에 열지 않는다.
|
||||
7. 테스트 종료 후 Windows VM, public DNS, test clients와 secret의 보존·폐기 여부를 Redmine에 기록한다.
|
||||
|
||||
## 6. Entra ID로 전환할 때
|
||||
|
||||
Entra tenant가 확보되면 AD DS/bridge 테스트에서 확인한 `issuer + immutable subject -> CB_APP_USER -> DDS END USER` 계약은 유지한다. 바뀌는 부분은 token issuer와 JWKS 검증 설정뿐이다. Entra의 claim 이름(`oid`, `sub`, `preferred_username` 등)은 실제 발급 토큰을 확인한 뒤 결정하며, `sub` 단독이 아니라 tenant/issuer 경계를 반드시 포함한다.
|
||||
|
||||
## 7. 완료 기준
|
||||
|
||||
- [x] `dds.test` AD forest와 두 테스트 사용자가 생성되었다.
|
||||
- [x] Keycloak LDAP bridge가 HTTPS OIDC JWT를 발급하고 각 사용자가 서로 다른 안정 subject를 가진다.
|
||||
- [x] MCP가 JWT signature/issuer/audience를 검증하고 `issuer + sub` 매핑을 해석한다.
|
||||
- [x] subject 매핑을 통해 각 요청에 대응하는 DDS END USER context만 attach된다.
|
||||
- [x] 서로 다른 권한의 동일 MCP 호출에서 데이터 행/열 결과가 달라진다.
|
||||
- [ ] 미매핑·만료·issuer/audience 불일치 요청은 데이터 접근 전에 거부된다.
|
||||
- [ ] 종료 시 테스트 VM과 전용 네트워크 리소스의 정리 여부 및 비용 상태를 Redmine에 기록한다.
|
||||
151
docs/design/744-windows-ad-dds-end-user-mapping/cookbook.md
Normal file
151
docs/design/744-windows-ad-dds-end-user-mapping/cookbook.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# Cookbook: OCI AD Bridge로 DDS MCP 사용자 인증 전환
|
||||
|
||||
[개요로 돌아가기](README.md) · [아키텍처](architecture.md) · [트러블슈팅](troubleshooting.md)
|
||||
|
||||
## 적용 순서
|
||||
|
||||
Keycloak을 삭제하지 않는다. 아래 단계를 순서대로 끝내고 Alice/Bob DDS 결과를 확인한 뒤에만 AIPF의 기본 MCP source를 OCI 경로로 바꾼다.
|
||||
|
||||
| 단계 | 작업 | 성공 판정 | 실패 시 |
|
||||
|---:|---|---|---|
|
||||
| 0 | AD·네트워크·관리 경로 점검 | AD/LDAPS/OCI HTTPS 연결 가능 | [Windows/LDAPS](troubleshooting.md#windows-ad-bridge) |
|
||||
| 1 | OCI AD Bridge 생성·Windows client 설치 | Bridge `Connected` | [Windows/AD Bridge](troubleshooting.md#windows-ad-bridge) |
|
||||
| 2 | AD OU/그룹 동기화 | OCI Domain에 Alice/Bob 표시 | [동기화](troubleshooting.md#동기화와-delegated-authentication) |
|
||||
| 3 | delegated authentication 시험·활성화 | AD 비밀번호 로그인 성공 | [동기화](troubleshooting.md#동기화와-delegated-authentication) |
|
||||
| 4 | AIPF OAuth source 등록 | OCI 로그인 → callback 완료 | [OAuth/AIPF](troubleshooting.md#oci-oauth와-aipf) |
|
||||
| 5 | MCP issuer/audience·DB binding 교체 | OCI JWT 검증·DDS mapping 성공 | [MCP/DDS](troubleshooting.md#mcp와-dds) |
|
||||
| 6 | Alice/Bob 비교 및 Keycloak 정리 판단 | Alice 1건, Bob 거부 | [권한](troubleshooting.md#mcp와-dds) |
|
||||
|
||||
## 0. 사전 점검
|
||||
|
||||
- AD Domain: `dds.test`
|
||||
- OCI Identity Domain: `identityAPAC`
|
||||
- Bridge 설치 위치: 운영은 domain-joined Windows member server 권장. 이 PoC는 격리된 AD VM에서 설치 가능 여부를 검증한다.
|
||||
- 네트워크: Bridge host → OCI Domain HTTPS 443, Bridge host → AD LDAPS 636
|
||||
- AD Bridge service account: 동기화 대상 OU 읽기, `cn=Deleted Objects` 읽기, delegated authentication에 필요한 password/lockout attribute 최소 권한
|
||||
- 동기화 대상은 기본 `CN=Users` container가 아니라 Bridge가 선택 가능한 OU에 둔다. 이 PoC는 `OU=Users,OU=DDS-PoC,DC=dds,DC=test` 및 `OU=Groups,OU=DDS-PoC,DC=dds,DC=test`를 사용한다.
|
||||
- OCI User 생성에 필요한 AD 사용자 속성은 최소 `sAMAccountName`, Given Name, Surname, `mail`이다. `mail`은 OCI가 허용하는 RFC 5322 형식의 주소여야 하며, `.test` 같은 내부 TLD는 거부될 수 있다.
|
||||
|
||||
현재 PoC Windows VM은 WinRM HTTPS(5986) 원격 실행이 확인됐다. OCI Run Command는 여전히 `ACCEPTED`에 머물 수 있으므로 installer 실행 수단으로 사용하지 않고 WinRM을 사용한다.
|
||||
|
||||
## 1. OCI AD Bridge 생성과 설치
|
||||
|
||||
1. OCI Console에서 **Identity & Security → Domains → identityAPAC → Directory integrations → Add → Microsoft Active Directory Bridge**를 연다.
|
||||
2. 표시되는 **Bridge client ID/secret**과 Domain URL을 secret store에 보관한다.
|
||||
3. OCI Console에서 내려받은 Bridge installer를 domain-joined Windows로 안전하게 전달한다. 현재 확보한 검증 대상 artifact는 `ad-id-bridge-23.2.92-2301160723.exe`다.
|
||||
4. installer에서 OCI Domain URL/client credential 및 AD Bridge service account를 입력한다.
|
||||
5. **LDAPS**를 선택하고 연결 시험을 통과한다.
|
||||
6. Directory integrations에서 사용자·그룹 OU를 최소 범위로 선택하고 initial sync를 실행한다.
|
||||
|
||||
Bridge client secret은 AIPF OAuth client secret 및 DB service client secret과 다르다. 각 secret을 서로 대체해 입력하지 않는다.
|
||||
|
||||
### 1.1 Installer artifact 관리
|
||||
|
||||
| 항목 | 이 PoC 값 | 적용 원칙 |
|
||||
|---|---|---|
|
||||
| 파일명 | `ad-id-bridge-23.2.92-2301160723.exe` | OCI Directory integrations 화면에서 내려받은 Bridge별 installer를 사용한다. |
|
||||
| 버전 | `23.2.92` | Console이 제공하는 최신 호환 installer인지 설치 직전에 확인한다. |
|
||||
| SHA-256 | `9388dbec5a76dfd19e6d3d5079e8cdccd00f4227e9aed36483961a8d68cdf19d` | 전달 전·후 checksum이 일치해야 한다. |
|
||||
| 원본 위치 | 로컬 `~/Downloads/` (Git 미포함) | 설치 파일·Bridge client secret·AD 비밀번호를 저장소에 commit하지 않는다. |
|
||||
| PoC 대상 위치 | `C:\DDS\installers\ad-id-bridge-23.2.92-2301160723.exe` | Windows에서 같은 SHA-256을 확인한 뒤 실행한다. |
|
||||
|
||||
입력값의 출처는 다음과 같다.
|
||||
|
||||
| installer 입력값 | 출처 | 성공 판정 |
|
||||
|---|---|---|
|
||||
| Identity Domain URL, Bridge client ID/secret | OCI Console의 해당 **Directory integration** 설치 화면 | Installer의 OCI 연결 시험 성공 |
|
||||
| AD Bridge account | `dds.test` AD에서 최소 권한으로 만든 전용 service account | LDAPS 연결 시험 및 initial sync 성공 |
|
||||
| AD server/SSL | `dds.test` LDAPS TCP 636 | 인증서 신뢰 오류 없이 연결 성공 |
|
||||
|
||||
실패하면 [Windows/AD Bridge 문제 해결](troubleshooting.md#windows-ad-bridge)을 먼저 확인한다. installer와 client secret은 Bridge 생성 화면에서 다시 내려받거나 rotation하며, 채팅·문서·명령 이력에 secret 값을 남기지 않는다.
|
||||
|
||||
### 1.2 설치 실행 방식
|
||||
|
||||
이 버전은 WiX Bootstrapper 기반 installer다. `/quiet`으로 실행하면 **response file이 없다는 이유로 종료**하므로, response file 형식이 검증되기 전에는 silent 설치를 사용하지 않는다.
|
||||
|
||||
1. Windows VM에 RDP로 접속한다.
|
||||
2. `C:\DDS\installers\ad-id-bridge-23.2.92-2301160723.exe`를 **Run as administrator**로 실행한다.
|
||||
3. OCI Console의 Bridge 화면에서 확인한 Domain URL, Bridge client ID/secret을 입력하고 OCI 연결 시험을 성공시킨다.
|
||||
4. AD Bridge 전용 service account와 비밀번호를 입력하고 **Use SSL (LDAPS)**를 유지한 채 AD 연결 시험을 성공시킨다.
|
||||
5. 설치 완료 후 Directory integrations의 Bridge 상태가 `Partially configured` 또는 `Connected`로 바뀌는지 확인한다.
|
||||
|
||||
성공 후에만 [2. delegated authentication 활성화](#2-delegated-authentication-활성화)로 진행한다. silent response file을 확보한 경우에도 secret을 response file에 평문 보관하지 않으며, 사용 직후 삭제·rotation 절차를 적용한다.
|
||||
|
||||
### 1.3 LDAPS 인증서와 동기화 범위 구성
|
||||
|
||||
Bridge installer의 `LDAP server is unavailable`은 TCP 636이 열려 있더라도 AD DS가 유효한 LDAPS 인증서를 제공하지 않을 때 발생할 수 있다. PoC에서는 AD DS FQDN인 `hmm-ad-dss-test.dds.test`를 CN/SAN으로 하는 private server certificate를 Local Machine `My`에 설치하고, Bridge host의 Trusted Root에도 신뢰시켰다. AD DS가 새 인증서를 선택하도록 재부팅한 후 FQDN 기준 TLS handshake를 확인한다.
|
||||
|
||||
```powershell
|
||||
$fqdn = 'hmm-ad-dss-test.dds.test'
|
||||
$cert = New-SelfSignedCertificate -DnsName $fqdn, 'hmm-ad-dss-test' `
|
||||
-CertStoreLocation 'Cert:\LocalMachine\My' -Type SSLServerAuthentication
|
||||
Export-Certificate -Cert $cert -FilePath 'C:\DDS\certs\dds-ad-ldaps-root.cer'
|
||||
Import-Certificate -FilePath 'C:\DDS\certs\dds-ad-ldaps-root.cer' `
|
||||
-CertStoreLocation 'Cert:\LocalMachine\Root'
|
||||
```
|
||||
|
||||
운영에서는 self-signed 인증서 대신 사내 CA가 발급한 인증서를 사용한다. `ad.cloud-handson.com` 같은 OIDC 공개 로그인 주소는 LDAPS server name이 아니다. Bridge의 AD 연결은 내부 AD FQDN과 TCP 636을 사용한다.
|
||||
|
||||
Bridge의 OU 선택 화면은 **OU만** 표시하고 기본 `CN=Users` container는 표시하지 않는다. 테스트 계정이 기본 container에 있으면 다음과 같이 전용 OU와 그룹을 만든 뒤 이동한다.
|
||||
|
||||
```text
|
||||
DC=dds,DC=test
|
||||
└─ OU=DDS-PoC
|
||||
├─ OU=Users ← dds-alice, dds-bob
|
||||
└─ OU=Groups ← DDS-DDS-Users
|
||||
```
|
||||
|
||||
`Edit configuration`에서 Users pane에는 `Users`, Groups pane에는 `Groups`만 선택한다. 상위 `dds.test` 또는 `DDS-PoC`를 Include hierarchy와 함께 선택하면 모든 하위 OU가 자동 선택되므로 선택하지 않는다. Supported operations의 AD 역방향 변경 항목은 모두 해제한다. import frequency를 설정하고, delegated authentication을 사용할 계획이면 **Enable local authentication**을 선택하고 **Enable federated authentication**은 해제한다. `Save` 뒤의 **Save Configuration Changes? → OK**까지 눌러야 상태가 `Configured`가 된다.
|
||||
|
||||
### 1.4 Import와 사용자 속성 검증
|
||||
|
||||
Bridge Action 메뉴의 **Import** 또는 configuration 저장으로 full sync를 실행한다. 성공 판정은 OCI Console의 Last import status에서 `Users imported from Active directory = 2`, `Groups imported from Active directory = 1`, failed 값이 모두 `0`인 것이다.
|
||||
|
||||
| AD 사용자 속성 | PoC 예시 | OCI 매핑 목적 |
|
||||
|---|---|---|
|
||||
| `sAMAccountName` | `dds-alice` | OCI User Name |
|
||||
| Given Name / Surname | `Alice` / `DDS` | OCI 필수 `name` |
|
||||
| `mail` | `dds-alice@cloud-handson.com` | OCI Primary Email |
|
||||
|
||||
속성을 보완한 뒤에도 이전 실패 사용자가 재시도되지 않으면 Users/Groups OU 선택을 모두 해제해 Save/OK하고, 다시 필요한 OU만 선택해 Save/OK한다. 이 절차는 full sync를 강제한다. 성공 여부는 OCI Domain Users/Groups와 [동기화 문제 해결](troubleshooting.md#동기화와-delegated-authentication)을 함께 확인한다.
|
||||
|
||||
## 2. delegated authentication 활성화
|
||||
|
||||
1. OCI Domain에서 동기화된 `dds-alice`, `dds-bob`을 확인한다.
|
||||
2. **Security → Delegated authentication → Test Delegated Authentication**에서 각 AD 계정/AD 비밀번호를 시험한다.
|
||||
3. 두 계정이 성공한 뒤에만 `Activate Delegated Authentication`을 켠다.
|
||||
|
||||
이후 OCI 로그인 화면에 입력한 비밀번호는 Bridge를 거쳐 AD DS에서 검증된다. OCI Domain은 비밀번호 원천이 아니라 OIDC issuer다.
|
||||
|
||||
## 3. AIPF OCI OAuth client
|
||||
|
||||
`AIPF_DDS_AD_TEST`는 AIPF 전용 confidential client다.
|
||||
|
||||
| 설정 | 값 |
|
||||
|---|---|
|
||||
| Grant | `authorization_code`, `refresh_token` |
|
||||
| Redirect URI | `https://aipf.cloud-handson.com/agentFactory/v1/tools/mcp/callback` 및 `https://aipf.cloud-handson.com/v1/tools/mcp/callback` |
|
||||
| Scope | `openid profile email offline_access` |
|
||||
| Authorization URL | discovery의 `authorization_endpoint` |
|
||||
| Token / Refresh URL | discovery의 `token_endpoint` |
|
||||
|
||||
discovery URL은 `https://<identity-domain>/.well-known/openid-configuration`이다. endpoint를 추측해 입력하지 않는다. local test 환경의 client credential은 git-ignore된 `.runtime/aipf-dds-oci-ad-client.env`에만 보관한다.
|
||||
|
||||
## 4. AIPF source와 MCP 전환
|
||||
|
||||
1. AIPF에서 기존 Keycloak source를 삭제하지 않고 새 source를 만든다.
|
||||
2. Server URL은 `https://hmm-backoffice.cloud-handson.com/mcp/dds/sse`를 유지한다.
|
||||
3. Authentication mode를 `OAuth`로 선택하고 OCI client ID/secret과 discovery endpoint를 입력한다.
|
||||
4. OCI login에서 Alice로 로그인한 뒤 받은 access token의 `iss`, `aud`, `sub`를 안전하게 확인한다.
|
||||
5. MCP의 issuer/audience와 `CB_EXTERNAL_IDENTITY_BINDING`을 OCI claim 기준으로 함께 바꾼다.
|
||||
6. Alice/Bob 권한 비교가 끝난 후에만 기존 source를 해제한다.
|
||||
|
||||
## 5. 검증과 rollback
|
||||
|
||||
| 검증 | 성공 |
|
||||
|---|---|
|
||||
| Alice `휴가` 검색 | `휴가 정책 - Alice 전용 테스트` 1건 |
|
||||
| Bob 같은 검색 | 권한 없는 보호 객체가 default deny |
|
||||
| 잘못된/만료/미매핑 OCI JWT | DB query 이전에 거부 |
|
||||
|
||||
실패 시 MCP issuer/audience와 AIPF source를 Keycloak 값으로 되돌린다. DB service client, `DDS_U_1`/`DDS_U_2`, DATA GRANT는 OCI 사용자 OAuth 전환과 별개이므로 rollback 대상이 아니다.
|
||||
@@ -0,0 +1,68 @@
|
||||
# 트러블슈팅: OCI AD Bridge · OAuth · DDS MCP
|
||||
|
||||
[개요로 돌아가기](README.md) · [적용 Cookbook](cookbook.md) · [아키텍처](architecture.md)
|
||||
|
||||
## Windows AD Bridge
|
||||
|
||||
| 증상 | 원인 확인 | 해결 |
|
||||
|---|---|---|
|
||||
| WinRM HTTPS TCP/5986 `Connection timed out` | OCI NSG에 관리 workstation `/32`의 TCP 5986 인바운드가 있는지 먼저 확인한다. 규칙을 추가한 뒤에도 timeout이면 Windows 내부 listener/firewall 문제다. | RDP에서 `winrm enumerate winrm/config/listener`, `Get-NetFirewallRule -DisplayGroup 'Windows Remote Management'`로 확인하고 HTTPS listener와 방화벽 rule을 구성한다. Bridge 자체 오류가 아니다. |
|
||||
| OCI Run Command plugin은 `RUNNING`인데 command가 `ACCEPTED`/`VISIBLE` | 단순 `echo`도 실행되지 않으면 script 문제가 아님 | Windows Oracle Cloud Agent/Run Command service, outbound OCI 연결, plugin log를 RDP에서 점검한다. |
|
||||
| AD Bridge installer가 `/quiet`에서 `No response file specified for silent install`으로 종료 | 이 WiX 기반 버전은 silent 설치에 response file이 필수다. | 임의의 response file을 만들지 말고 RDP의 관리자 설치 UI로 진행한다. 검증된 response file을 확보한 경우에만 secret 보관/삭제 정책을 적용해 자동화한다. |
|
||||
| installer에서 `LDAP server is unavailable` | TCP 636 open만 확인하지 말고 AD DS FQDN으로 TLS handshake를 시험한다. handshake가 즉시 종료되면 AD DS LDAPS certificate 문제다. | AD DS FQDN CN/SAN, Server Authentication EKU, private key를 갖춘 certificate를 Local Machine `My`에 설치하고 issuer를 Bridge host Trusted Root에 신뢰시킨 뒤 AD DS 재시작/VM 재부팅한다. |
|
||||
| LDAPS certificate 오류 | Bridge host가 AD DS server/CA certificate를 신뢰하는지 확인 | CA chain을 Windows trust store에 배포한다. OIDC 공개 hostname이 아니라 실제 AD DS FQDN을 certificate와 LDAP endpoint에 사용한다. |
|
||||
| Bridge `Connected`가 되지 않음 | OCI 443, AD 636, Bridge service account credential/권한 확인 | NSG/proxy/firewall 및 최소 AD 권한을 순서대로 점검한다. |
|
||||
|
||||
## Windows 원격 관리 경로가 막힌 경우
|
||||
|
||||
이 PoC VM에서는 OCI NSG의 TCP 5986 누락을 보완했어도 Windows가 HTTPS WinRM 요청에 응답하지 않았다. 따라서 **NSG rule 추가만으로 WinRM이 활성화되는 것은 아니다.**
|
||||
|
||||
RDP로 `DDS\\opc`로 로그인한 뒤 Administrator PowerShell에서 다음 순서로 점검한다. 운영에서는 management source를 반드시 고정 IP 또는 private subnet으로 제한한다.
|
||||
|
||||
```powershell
|
||||
winrm quickconfig
|
||||
winrm enumerate winrm/config/listener
|
||||
Get-NetFirewallRule -DisplayGroup 'Windows Remote Management' |
|
||||
Select-Object DisplayName, Enabled, Direction, Action
|
||||
```
|
||||
|
||||
HTTPS listener가 없다면 서버 인증서의 thumbprint를 지정해 생성하고, TCP 5986 firewall rule을 enable한 뒤 외부에서 `/wsman` endpoint를 재확인한다. OCI Run Command가 `ACCEPTED`/`VISIBLE`에 머물면 그 기능으로 installer를 실행하지 말고, Windows Oracle Cloud Agent와 outbound OCI 연결을 RDP에서 복구한 후 다시 시도한다.
|
||||
|
||||
## 동기화와 delegated authentication
|
||||
|
||||
| 증상 | 원인 확인 | 해결 |
|
||||
|---|---|---|
|
||||
| Alice/Bob이 OCI Domain에 보이지 않음 | 선택한 사용자 OU/하위 OU와 initial sync 상태 | OU 범위와 filter를 수정하고 sync를 재실행한다. |
|
||||
| OU 선택 화면에 `CN=Users` 또는 테스트 계정이 보이지 않음 | 화면은 AD object가 아니라 **OU만** 나열한다. 기본 Users는 container다. | 전용 Users/Groups OU를 만들고 test user/group을 이동한 뒤 browser를 새로고침한다. OU 이름만 선택하면 되며 그 화면에서 계정 내용은 표시되지 않는다. |
|
||||
| 상위 `dds.test` 선택 시 child OU가 자동 선택됨 | Include hierarchy가 선택된 parent OU에 적용됨 | parent selection을 해제하고 Users pane은 `Users`, Groups pane은 `Groups`만 직접 선택한다. |
|
||||
| `Missing required attribute(s): name` | AD Given Name 또는 Surname이 비어 있어 OCI `name` complex attribute를 만들 수 없음 | AD test user의 Given Name, Surname, Display Name을 채운 뒤 full sync한다. |
|
||||
| `primaryEmailNotSpecified` | AD `mail` 속성이 비어 있음 | 유효한 Primary Email 형식의 `mail` 값을 설정한다. |
|
||||
| `invalidEmailFormat` | `.test` 같은 내부 TLD가 OCI email validator에서 거부됨 | PoC라도 RFC 5322 형식으로 OCI가 허용하는 domain의 email을 사용한다. 실제 notification이 필요 없으면 welcome notification을 끈다. |
|
||||
| 속성을 고쳤는데 `Users synced = 0` | Bridge가 이전 실패 user를 재시도 제외하거나 incremental sync만 수행 | Users/Groups OU 선택을 모두 해제해 Save/OK한 뒤 다시 선택해 Save/OK하여 full sync를 강제하고 Import 결과를 재확인한다. |
|
||||
| OCI 로그인 비밀번호가 실패 | delegated authentication test에서 동일 AD 계정으로 재현 | AD 비밀번호, Bridge AD 연결, service account delegated-auth 권한을 확인한다. |
|
||||
| AD 비밀번호를 OCI local password로 입력하려 함 | delegated authentication 활성화 여부 | 성공 시험 후 활성화한다. 활성화 뒤 실제 비밀번호 원천은 AD다. |
|
||||
| `Security → Delegated authentication` 메뉴가 보이지 않음 | Identity Domain의 delegated authentication capability가 테넌트에서 활성화되지 않았을 수 있다. | OCI Console UI를 찾는 문제로 가정하지 말고 domain capability/서비스 등급을 확인한다. OCI tenancy administrator 또는 Oracle Support에 delegated authentication enablement를 요청한다. |
|
||||
| Identity Source PATCH가 `Delegated Authentication is not yet enabled. This feature is currently in beta phase.`로 400 반환 | 해당 Identity Domain에서 delegated authentication feature가 enable되지 않았다. Bridge 설치·동기화·LDAPS 상태와는 별개인 OCI control-plane 제한이다. | 기능 enablement 전에는 OCI OAuth 로그인에 AD 비밀번호를 사용할 수 없다. Keycloak 경로를 유지하거나 OCI local/federated 인증을 임시로 사용하고, enablement 완료 후 delegated auth test/activate를 재개한다. |
|
||||
|
||||
## OCI OAuth와 AIPF
|
||||
|
||||
| 증상/오류 | 원인 | 해결 |
|
||||
|---|---|---|
|
||||
| `/admin/v1/admin/v1/Apps` 및 401 | `oci identity-domains --endpoint`에 `/admin/v1`까지 넣음 | CLI에는 Domain base URL만 사용한다. raw request target에만 `/admin/v1`을 넣는다. |
|
||||
| `No such option: --header` | `oci raw-request` 옵션명 오류 | `--request-headers '{"Content-Type":"application/json"}'`를 사용한다. |
|
||||
| `Missing required attribute(s): basedOnTemplate` | confidential client app template 누락 | `basedOnTemplate.value=CustomWebAppTemplateId`를 지정한다. |
|
||||
| authorize URL이 302 대신 200 | OCI Domain이 sign-in HTML과 session cookie를 반환 | 정상이다. browser에서 OCI login UI가 표시되는지 확인한다. |
|
||||
| AIPF callback 오류 | redirect URI가 두 AIPF 경로 중 실제 요청 경로와 다름 | `/agentFactory/.../callback`과 `/v1/.../callback` 둘 다 등록한다. |
|
||||
| 이전 사용자로 자동 로그인 | OCI Domain browser SSO session 유지 | OCI logout 후 새 MCP source를 연결한다. |
|
||||
|
||||
## MCP와 DDS
|
||||
|
||||
| 증상 | 원인 | 해결 |
|
||||
|---|---|---|
|
||||
| MCP `401` / tools discovery 실패 | OCI issuer/audience가 runtime에 반영되지 않았거나 token 만료 | discovery/JWT claim을 기준으로 issuer·audience를 설정한다. |
|
||||
| token 검증은 되지만 `AUTHORIZATION_DENIED` | OCI `iss + sub` binding 미등록/비활성 | `CB_EXTERNAL_IDENTITY_BINDING`과 DDS END USER mapping을 함께 확인한다. |
|
||||
| `DDS_CONTEXT_UNAVAILABLE` | DB service client/scope/domain URL 설정 문제 | `DDS_MCP_SERVICE_TEST`, `DDS_ORACLE_DB_TEST`, `DB_ACCESS_SCOPE`, DB application identity를 확인한다. |
|
||||
| `ORA-52602` | database-access token issuer/resource/scope 불일치 | DB의 OCI Domain URL 정규형(`:443` 포함), resource app ID/scope를 맞춘다. |
|
||||
| Alice 성공, Bob “DDS 보호 객체” | Bob DATA GRANT 없음 | 의도된 default deny다. 정책상 필요할 때만 최소 grant를 추가한다. |
|
||||
|
||||
외부 오류 메시지에는 SQL, table명, secret을 노출하지 않는다. 내부 감사에는 correlation ID, 내부 user ID, 선택 DDS END USER, allow/deny 결과를 남긴다.
|
||||
@@ -0,0 +1,55 @@
|
||||
# HMM Select AI annotation 제외 프로파일 비교
|
||||
|
||||
Redmine: #749
|
||||
|
||||
상태: Approved
|
||||
|
||||
구현 대상: `database/adb/85_hmm_hr_select_ai_no_annotation_profile.sql`,
|
||||
`database/adb/86_hmm_select_ai_annotation_benchmark.sql`
|
||||
|
||||
## 목적
|
||||
|
||||
HMM HR Select AI에서 Oracle table/column annotation을 프롬프트에 포함할 때와 제외할 때의 응답
|
||||
시간과 SQL 생성 결과를 같은 조건으로 비교한다. 운영 프로파일과 MCP 설정은 변경하지 않는다.
|
||||
|
||||
## 범위와 결정사항
|
||||
|
||||
- 기준 프로파일은 `HMM_HR_DATA_GPT54_PROFILE`이며 현재 `annotations=true`다.
|
||||
- 비교 프로파일은 `HMM_HR_DATA_GPT54_NOANN_PROFILE`로 만들고 `annotations=false`를 명시한다.
|
||||
- provider, credential, model, region, compartment, object list, temperature, max tokens는 동일하게 유지한다.
|
||||
- 같은 한국어 질문으로 `showprompt` 크기·시간과 `showsql` 생성 시간·성공 여부를 교차 반복 측정한다.
|
||||
- 한국어 질문은 SQLcl에 직접 넣지 않고 UTF-8 Base64를 Oracle 안에서 복원한다.
|
||||
- 측정 결과만으로 운영 프로파일을 자동 전환하지 않는다.
|
||||
|
||||
## 전체 구성
|
||||
|
||||
```text
|
||||
동일 HR 질문
|
||||
├─ HMM_HR_DATA_GPT54_PROFILE ─ annotations=true ─ showprompt/showsql
|
||||
└─ HMM_HR_DATA_GPT54_NOANN_PROFILE ─ annotations=false ─ showprompt/showsql
|
||||
│
|
||||
시간·prompt 크기·SQL 비교
|
||||
```
|
||||
|
||||
두 경로의 유일한 의도적 차이는 `annotations`다. 기존 선사 Federation 프로파일은 이미 annotation을
|
||||
사용하지 않으므로 이번 A/B 대상이 아니다.
|
||||
|
||||
## 성공 기준
|
||||
|
||||
- 두 프로파일의 비교 대상 속성이 `annotations` 외에는 같다.
|
||||
- 각 프로파일이 같은 질문에 유효한 읽기 전용 SQL을 생성한다.
|
||||
- 측정 회차별 시간, 성공 여부, 생성 SQL 길이를 남긴다.
|
||||
- 기존 프로파일과 운영 `BACKOFFICE_SELECT_AI_PROFILE` 값이 바뀌지 않는다.
|
||||
|
||||
## 문서 지도
|
||||
|
||||
- [비교 설계](architecture.md)
|
||||
- [생성·측정·롤백 절차](cookbook.md)
|
||||
- [측정 결과](results.md)
|
||||
- [문제 해결](troubleshooting.md)
|
||||
|
||||
## 현재 상태
|
||||
|
||||
2026-08-11 비교 프로파일 생성과 3회 교차 측정을 완료했다. 현재 HR object list에는 실제
|
||||
annotation이 0건이어서 prompt 크기는 34자만 줄었고, `showsql` 평균은 annotation 사용 2.453초,
|
||||
제외 2.483초로 의미 있는 개선이 없었다. 운영 프로파일은 변경하지 않았다.
|
||||
@@ -0,0 +1,49 @@
|
||||
# 비교 설계
|
||||
|
||||
[개요](README.md) · [실행 절차](cookbook.md) · [측정 결과](results.md) · [문제 해결](troubleshooting.md)
|
||||
|
||||
## 비교 대상
|
||||
|
||||
| 속성 | annotation 사용 | annotation 제외 |
|
||||
|---|---|---|
|
||||
| 프로파일 | `HMM_HR_DATA_GPT54_PROFILE` | `HMM_HR_DATA_GPT54_NOANN_PROFILE` |
|
||||
| provider | `oci` | 동일 |
|
||||
| model | `openai.gpt-5.4-mini` | 동일 |
|
||||
| object list | HMM HR 5개 객체 | 동일 |
|
||||
| temperature | `0.1` | 동일 |
|
||||
| max tokens | `1500` | 동일 |
|
||||
| annotations | `true` | `false` |
|
||||
|
||||
credential 이름과 compartment OCID는 비밀값은 아니지만 환경 종속값이므로 문서에 복사하지 않고
|
||||
DB 원본 프로파일을 기준으로 검증한다. credential 원문이나 토큰은 조회·출력하지 않는다.
|
||||
|
||||
## 측정 방식
|
||||
|
||||
```text
|
||||
run 1: annotation → no annotation
|
||||
run 2: no annotation → annotation
|
||||
run 3: annotation → no annotation
|
||||
```
|
||||
|
||||
호출 순서를 번갈아 배치해 첫 호출 캐시와 일시적 모델 지연이 한쪽에만 몰리는 현상을 줄인다.
|
||||
각 호출은 `DBMS_CLOUD_AI.GENERATE(prompt, profile, action)` 한 번의 경과 시간을
|
||||
`DBMS_UTILITY.GET_TIME`으로 측정한다.
|
||||
|
||||
- `showprompt`: 모델에 전달되는 metadata prompt 크기와 구성 비용 비교
|
||||
- `showsql`: 실제 SQL 생성 시간과 성공 여부 비교
|
||||
|
||||
생성 SQL은 실행하지 않는다. SQL 생성 품질은 `SELECT`/`WITH` 시작 여부, 길이와 주요 객체 사용을
|
||||
검토한다. VPD 결과 행 비교는 운영 프로파일 전환을 결정한 뒤 별도 MCP 회귀 검증에서 수행한다.
|
||||
|
||||
## 안전 경계
|
||||
|
||||
- 기존 프로파일에는 `SET_ATTRIBUTE`, disable, drop을 실행하지 않는다.
|
||||
- 비교 프로파일이 이미 있으면 덮어쓰지 않고 정의를 검증한다.
|
||||
- 벤치마크는 DDL/DML을 생성하거나 실행하지 않고 `showprompt`와 `showsql`만 호출한다.
|
||||
- 새 프로파일은 운영 MCP 설정에 자동 연결하지 않는다.
|
||||
|
||||
Oracle 공식 문서에 따르면 `annotations=true`는 table/column annotation을 LLM metadata에 포함하며,
|
||||
프로파일 속성은 `DBA_CLOUD_AI_PROFILE_ATTRIBUTES`에서 확인할 수 있다.
|
||||
|
||||
- [Oracle DBMS_CLOUD_AI package](https://docs.oracle.com/en/database/oracle/oracle-database/26/arpls/dbms_cloud_ai1.html)
|
||||
- [Oracle DBMS_CLOUD_AI views](https://docs.oracle.com/en-us/iaas/autonomous-database-serverless/doc/dbms-cloud-ai-views.html)
|
||||
@@ -0,0 +1,65 @@
|
||||
# 생성·측정·롤백 절차
|
||||
|
||||
[개요](README.md) · [비교 설계](architecture.md) · [측정 결과](results.md) · [문제 해결](troubleshooting.md)
|
||||
|
||||
## 1. 준비
|
||||
|
||||
- ADMIN으로 HMM ADB에 연결한다.
|
||||
- `HMM_HR_DATA_GPT54_PROFILE`이 `ENABLED`이고 `annotations=true`인지 확인한다.
|
||||
- 운영 `BACKOFFICE_SELECT_AI_PROFILE` 값을 기록하되 credential과 비밀번호는 출력하지 않는다.
|
||||
|
||||
성공 판정: 원본 프로파일과 전체 속성 목록을 읽을 수 있다.
|
||||
|
||||
실패 시: [원본 프로파일이 없거나 소유자가 다름](troubleshooting.md#원본-프로파일이-없거나-소유자가-다름)
|
||||
|
||||
## 2. 비교 프로파일 생성
|
||||
|
||||
```text
|
||||
database/adb/85_hmm_hr_select_ai_no_annotation_profile.sql
|
||||
```
|
||||
|
||||
스크립트는 비교 프로파일이 없을 때만 생성한다. 생성 후 원본과 비교 프로파일의 속성을 조회해
|
||||
`annotations` 외의 차이가 없는지 확인한다.
|
||||
|
||||
성공 판정: `HMM_HR_DATA_GPT54_NOANN_PROFILE`이 `ENABLED`, `annotations=false`다.
|
||||
|
||||
실패 시: [비교 프로파일이 이미 있지만 속성이 다름](troubleshooting.md#비교-프로파일이-이미-있지만-속성이-다름)
|
||||
|
||||
## 3. A/B 측정
|
||||
|
||||
```text
|
||||
database/adb/86_hmm_select_ai_annotation_benchmark.sql
|
||||
```
|
||||
|
||||
동일 질문을 UTF-8 Base64에서 복원하고, 두 프로파일의 `showprompt`와 `showsql`을 번갈아 3회씩
|
||||
호출한다. `BENCHMARK|...` 행을 결과 파일에 저장하고 평균·중앙값을 계산한다.
|
||||
|
||||
성공 판정:
|
||||
|
||||
- 두 프로파일 모두 3회 결과가 있다.
|
||||
- `showsql`이 읽기 전용 SQL을 반환한다.
|
||||
- 시간과 prompt/SQL 길이를 비교할 수 있다.
|
||||
|
||||
실패 시: [호출이 간헐적으로 실패하거나 시간이 크게 흔들림](troubleshooting.md#호출이-간헐적으로-실패하거나-시간이-크게-흔들림)
|
||||
|
||||
## 4. 운영 전환 판단
|
||||
|
||||
이번 실험에서는 운영 값을 바꾸지 않는다. 속도 개선이 반복 확인되고 SQL 품질이 유지될 때만
|
||||
별도 변경으로 `BACKOFFICE_SELECT_AI_PROFILE` 전환과 MCP VPD 회귀 검증을 수행한다.
|
||||
|
||||
2026-08-11 측정에서는 의미 있는 속도 개선이 확인되지 않았으므로 전환하지 않았다. 자세한 수치는
|
||||
[측정 결과](results.md)를 본다.
|
||||
|
||||
## 5. 롤백
|
||||
|
||||
비교 프로파일이 문제를 일으키면 먼저 disable한다.
|
||||
|
||||
```sql
|
||||
BEGIN
|
||||
DBMS_CLOUD_AI.DISABLE_PROFILE('HMM_HR_DATA_GPT54_NOANN_PROFILE');
|
||||
END;
|
||||
/
|
||||
```
|
||||
|
||||
운영 프로파일은 실험 중 변경하지 않으므로 서비스 롤백은 필요 없다. 프로파일 삭제는 측정 이력과
|
||||
의존성을 확인한 뒤 별도 승인하에 수행한다.
|
||||
@@ -0,0 +1,49 @@
|
||||
# 측정 결과
|
||||
|
||||
[개요](README.md) · [비교 설계](architecture.md) · [실행 절차](cookbook.md) · [문제 해결](troubleshooting.md)
|
||||
|
||||
## 결론
|
||||
|
||||
현재 HMM HR 데이터에서는 annotation 제외에 따른 일관된 속도 개선이 확인되지 않았다.
|
||||
annotation 사용 프로파일의 object list에 실제 table/column annotation이 0건이기 때문이다.
|
||||
운영 프로파일은 기존 값을 유지한다.
|
||||
|
||||
## 측정 조건
|
||||
|
||||
| 항목 | 값 |
|
||||
|---|---|
|
||||
| 측정일 | 2026-08-11 |
|
||||
| DB 연결 | ADMIN / `hmmaipoc_low` |
|
||||
| 모델 | `openai.gpt-5.4-mini` |
|
||||
| 질문 | 이번 달 팀원별 휴가 사용 현황 조회 |
|
||||
| 반복 | action별·profile별 3회, 호출 순서 교차 |
|
||||
| annotation 사용 | `HMM_HR_DATA_GPT54_PROFILE` |
|
||||
| annotation 제외 | `HMM_HR_DATA_GPT54_NOANN_PROFILE` |
|
||||
|
||||
한국어 질문은 UTF-8 Base64로 전달해 Oracle에서 복원했다. `showsql` 결과는 실행하지 않았다.
|
||||
|
||||
## 결과 요약
|
||||
|
||||
| action | 프로파일 | 평균 | 중앙값 | 최소 | 최대 | 결과 크기 |
|
||||
|---|---|---:|---:|---:|---:|---:|
|
||||
| `showprompt` | annotation 사용 | 693.3ms | 130ms | 120ms | 1,830ms | 3,188자 |
|
||||
| `showprompt` | annotation 제외 | 196.7ms | 130ms | 120ms | 340ms | 3,154자 |
|
||||
| `showsql` | annotation 사용 | 2,453.3ms | 2,430ms | 2,410ms | 2,520ms | 522~547자 |
|
||||
| `showsql` | annotation 제외 | 2,483.3ms | 2,370ms | 2,350ms | 2,730ms | 522~533자 |
|
||||
|
||||
`showprompt` 첫 회차의 1,830ms는 이후 120~130ms로 줄어 초기 metadata cache 영향으로 판단한다.
|
||||
중앙값은 두 프로파일 모두 130ms다. `showsql`은 annotation 제외 프로파일이 평균 기준 30ms 느리고,
|
||||
중앙값 기준 60ms 빠르므로 측정 편차 범위다.
|
||||
|
||||
## 품질 확인
|
||||
|
||||
- `showsql` 6회 모두 `SELECT` 또는 `WITH`로 시작하는 유효한 읽기 전용 SQL을 반환했다.
|
||||
- 회차별 SQL hash가 달라 생성 SQL은 완전히 결정적이지 않았다.
|
||||
- 두 프로파일의 prompt 크기 차이는 34자, 약 1.1%다.
|
||||
- HR object list 5개 테이블의 `ALL_ANNOTATIONS_USAGE` 집계는 0건, 0자다.
|
||||
|
||||
## 판단
|
||||
|
||||
현재 조건에서는 `annotations=false` 프로파일로 운영 전환할 근거가 없다. annotation metadata가 실제로
|
||||
많은 다른 object list에서는 결과가 달라질 수 있으므로, 그 경우 같은 스크립트로 다시 측정해야 한다.
|
||||
비교 프로파일은 후속 시험용으로 유지하되 MCP 운영 설정에는 연결하지 않는다.
|
||||
@@ -0,0 +1,46 @@
|
||||
# 문제 해결
|
||||
|
||||
[개요](README.md) · [비교 설계](architecture.md) · [실행 절차](cookbook.md) · [측정 결과](results.md)
|
||||
|
||||
## 원본 프로파일이 없거나 소유자가 다름
|
||||
|
||||
**증상**: `HMM_HR_DATA_GPT54_PROFILE` 조회 결과가 없거나 `CREATE_PROFILE` 권한 오류가 발생한다.
|
||||
|
||||
**원인**: 다른 DB 또는 다른 사용자로 접속했거나 프로파일 소유자가 ADMIN이 아니다.
|
||||
|
||||
**확인**: `DBA_CLOUD_AI_PROFILES`에서 owner와 profile name을 확인한다.
|
||||
|
||||
**해결**: HMM ADB 지갑·service alias와 ADMIN 연결을 다시 확인한다. 이름이 비슷한 프로파일을 임의로
|
||||
대체하지 않는다.
|
||||
|
||||
## 비교 프로파일이 이미 있지만 속성이 다름
|
||||
|
||||
**증상**: 비교 프로파일은 존재하지만 모델, object list, temperature 또는 annotations 값이 설계와 다르다.
|
||||
|
||||
**원인**: 이전 실험의 프로파일이 같은 이름으로 남아 있다.
|
||||
|
||||
**확인**: `DBA_CLOUD_AI_PROFILE_ATTRIBUTES`에서 두 프로파일을 나란히 비교한다.
|
||||
|
||||
**해결**: 기존 비교 프로파일을 덮어쓰지 않는다. 먼저 disable하고 이력·의존성을 확인한 뒤 새 버전
|
||||
이름을 사용하거나 별도 승인으로 정리한다.
|
||||
|
||||
## 호출이 간헐적으로 실패하거나 시간이 크게 흔들림
|
||||
|
||||
**증상**: 같은 프로파일에서도 회차별 `showsql` 시간이 크게 다르거나 LLM 오류가 발생한다.
|
||||
|
||||
**원인**: 모델 endpoint 부하, 첫 호출 metadata cache, 생성형 SQL의 비결정성일 수 있다.
|
||||
|
||||
**확인**: 두 프로파일을 번갈아 호출했는지, 각 3회 이상 결과가 있는지, 오류 코드가 프로파일 설정
|
||||
오류인지 외부 모델 오류인지 구분한다.
|
||||
|
||||
**해결**: 실패 회차를 숨기지 않고 기록한다. 같은 조건으로 추가 회차를 실행하고 평균뿐 아니라
|
||||
중앙값·최솟값·최댓값을 함께 비교한다.
|
||||
|
||||
## 한국어 질문이 깨져 SQL 품질이 달라짐
|
||||
|
||||
**증상**: 질문의 한글이 깨지거나 관련 없는 SQL이 생성된다.
|
||||
|
||||
**원인**: SQLcl을 통해 한국어 literal을 직접 전달했다.
|
||||
|
||||
**해결**: UTF-8 질문을 Base64 ASCII로 전달하고 Oracle에서 `UTL_I18N.RAW_TO_CHAR`로 복원한다.
|
||||
직접 SQL string 또는 `q'[...]'`를 사용하지 않는다.
|
||||
48
docs/design/hmm-html-report-mcp/README.md
Normal file
48
docs/design/hmm-html-report-mcp/README.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# HMM HTML 리포트 MCP
|
||||
|
||||
## 목적
|
||||
|
||||
선사 실적 Federation 조회의 구조화 결과를 HMM 기업 리포트 HTML로 표현한다. 리포트 도구는
|
||||
DB를 다시 조회하거나 자연어를 해석하지 않는다.
|
||||
|
||||
## 결정사항
|
||||
|
||||
- 기준 MCP endpoint는 `https://hmm-backoffice.cloud-handson.com/mcp` 하나이며, 별도 호환성 시험 endpoint로 교체하지 않는다.
|
||||
- 기존 조회 route `search_carrier_performance`는 DB Agent Tool `HMM_CARRIER_FEDERATION_SEARCH`를 그대로 호출한다. 이 경로가 자연어를 Select AI Federation으로 처리한다.
|
||||
- MCP 도구 `render_hmm_carrier_report`는 `reportJson` 문자열 하나를 입력으로 받는다.
|
||||
- 입력은 질문·답변 근거·조회 행으로 구성된 허용 JSON 계약이며, Oracle DB 함수는 템플릿에만 매핑한다.
|
||||
- 선사 실적 조회 MCP가 VPD를 적용한 데이터 접근 경계이고, 리포트 MCP는 표현 경계다.
|
||||
- 승인된 HTML 템플릿은 DB CLOB으로 버전 관리하고, 생성 HTML은 MCP 응답의 `html` 속성으로만 반환한다.
|
||||
- 제목은 질문 전체 문장을 복사하지 않는다. 포털의 제목 생성 지침이 요청 대상과 업무 범위만 남긴 짧은 보고서 제목을 만들고 renderer에 전달한다.
|
||||
- 같은 대화에서 데모 사용자를 전환해도 현재 선택 사용자 ID가 질문의 `내`와 제목 범위를 결정한다. 다른 사용자의 이전 대화는 현재 사용자의 문맥으로 사용하지 않는다.
|
||||
- HTML artifact가 반환되면 일반 답변은 HTML 표나 코드를 반복하지 않고 생성 완료와 조회 건수만 안내한다. 실제 표현은 `생성된 리포트` 영역 하나에서 담당한다.
|
||||
- 포털은 사용자 질문을 그대로 두 Tool에 재사용하지 않는다. 첫 조회에는 데이터 조건만 남긴 질문을 전달하고, `HTML로 보여줘` 같은 표현 요청은 renderer 선택과 제목 생성에만 사용한다.
|
||||
|
||||
## 전체 흐름
|
||||
|
||||
```text
|
||||
HMM 포털 → `https://hmm-backoffice.cloud-handson.com/mcp` → 데이터 조회 도구
|
||||
→ 포털의 범용 결과 정규화 → 이전 결과 입력형 렌더링 도구 → HTML 미리보기
|
||||
```
|
||||
|
||||
리포트에 보이는 값은 조회 결과 행에서 계산되므로, 자연어 답변과 별개로 재해석되지 않는다.
|
||||
|
||||
## 문서 지도
|
||||
|
||||
- [아키텍처와 입력 계약](architecture.md)
|
||||
- [적용·검증 절차](cookbook.md)
|
||||
- [문제 해결](troubleshooting.md)
|
||||
|
||||
## 현재 상태
|
||||
|
||||
Oracle DB의 custom Agent Tool과 템플릿 CLOB은 적용됐다. 포털은 리포트·차트·HTML 요청에서
|
||||
도구 이름을 고정하지 않고, 발견한 도구의 설명·입력 스키마를 기준으로 데이터 조회 뒤 렌더링을
|
||||
순차 호출하도록 운영 배포한다.
|
||||
|
||||
2026-08-10 운영 검증에서 같은 endpoint와 Bearer 문맥으로 기존 Select AI 조회 8건, renderer 입력
|
||||
8건, HTML 18,670자를 연속 호출해 확인했다. 조회 응답은 `response.result` 안의 JSON 배열 문자열로
|
||||
반환되므로 포털이 이를 범용적으로 구조화한다. HTML 템플릿에는 업무 샘플 행을 저장하지 않으며,
|
||||
호출 시 전달된 `report`와 `rows`만 표시한다.
|
||||
|
||||
2026-08-10 사용자 전환 회귀 검증에서는 E1001 제목이 팀장·팀원 범위를 유지하고, 같은 대화에서
|
||||
E1002로 전환한 `내 담당 선사` 제목은 E1002 범위로 생성되며 E1001 식별자가 섞이지 않음을 확인했다.
|
||||
131
docs/design/hmm-html-report-mcp/architecture.md
Normal file
131
docs/design/hmm-html-report-mcp/architecture.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# 아키텍처와 입력 계약
|
||||
|
||||
## 책임 경계
|
||||
|
||||
| 구성요소 | 책임 | DB 접근 |
|
||||
|---|---|---|
|
||||
| `search_carrier_performance` | 기존 `HMM_CARRIER_FEDERATION_SEARCH`를 통한 Bearer/VPD 기반 Select AI Federation 조회 | 허용 |
|
||||
| AI 웹 콘솔 | 도구 계약을 판별해 조회 결과를 정규화하고 렌더러를 후속 호출 | 없음 |
|
||||
| `render_hmm_carrier_report` | DB CLOB 템플릿에 허용된 JSON을 매핑 | 템플릿만 읽음 |
|
||||
| 브라우저 | 반환 HTML 표시·다운로드 | 없음 |
|
||||
|
||||
```text
|
||||
HMM portal ──► /mcp (Bearer) ──► Backoffice MCP facade ──► DB Agent Tool
|
||||
│
|
||||
VPD applied rows
|
||||
│
|
||||
Console
|
||||
│
|
||||
report MCP tool call
|
||||
│
|
||||
HMM_REPORT_TEMPLATES
|
||||
│
|
||||
HTML 응답
|
||||
```
|
||||
|
||||
리포트 MCP도 같은 Bearer 인증을 통과해야 하지만, 권한 판단은 조회 MCP에서 끝난다. 리포트
|
||||
입력의 임의 사용자 ID를 신뢰하거나 DB를 재조회하지 않는다.
|
||||
|
||||
## 포털의 범용 순차 호출 규칙
|
||||
|
||||
포털은 `render_hmm_carrier_report`라는 이름을 조건문에 넣지 않는다. 발견한 MCP 도구가 아래
|
||||
계약을 동시에 보이면 **이전 결과 입력형 렌더러**로 분류한다.
|
||||
|
||||
- 입력 스키마에 `reportJson`·`report_payload`처럼 리포트 JSON/payload를 받는 문자열이 있다.
|
||||
- 설명에 HTML/리포트/렌더링 의도와 `조회 결과`, `후속 처리`, `already-authorized`처럼 선행 결과를
|
||||
사용한다는 의도가 있다.
|
||||
|
||||
사용자가 리포트·보고서·대시보드·차트·HTML을 요청하고 이 렌더러가 발견되면, 기존 LLM 라우터는
|
||||
렌더러를 제외한 데이터 도구 중 하나를 먼저 선택한다. 첫 응답의 `items`, `results`, `rows` 또는
|
||||
`response.result` 안의 JSON 배열 문자열을 같은 방식으로 구조화하고, camelCase JSON으로 정규화해
|
||||
두 번째 도구에 전달한다. 포털은 렌더러의 `html` 응답을 iframe으로 표시한다. 이 규칙은 특정
|
||||
Tool 이름, 사용자 코드나 예상 행 수를 조건으로 사용하지 않는다.
|
||||
|
||||
## 변경 금지 경계
|
||||
|
||||
- `search_carrier_performance`의 DB target은 기존 `HMM_CARRIER_FEDERATION_SEARCH`다.
|
||||
- 별도 호환성 시험 서버 `hmm-mcp.cloud-handson.com`은 이 운영 경로를 대신하지 않는다.
|
||||
- HTML 추가를 이유로 조회 Agent Tool, Select AI profile, VPD 정책 또는 조회 package를 생성·교체하지 않는다.
|
||||
- renderer는 선행 결과만 표현하며 누락 행을 조회하거나 고정 샘플로 채우지 않는다.
|
||||
|
||||
## `reportJson` 계약
|
||||
|
||||
최상위에는 `report` 객체와 `rows` 배열만 허용한다. `report`에는 `id`, `category`, `title`,
|
||||
`generatedAt`, `requestedBy`, `question`, `answer`, `execution`, `evidence`, `limitation`을
|
||||
넣는다. 행에는 담당자·선사 식별자와 최신 KPI만 넣는다.
|
||||
|
||||
`report.title`은 사용자 질문 원문이 아니다. 포털이 모델에 다음 제목 계약을 지시해 만든 짧은
|
||||
업무 제목이다.
|
||||
|
||||
- `HTML로 보여줘`, `리포트로 만들어줘`와 같은 출력 형식·행동 문구는 제거한다.
|
||||
- 사용자·팀·업무 대상처럼 범위를 구분하는 식별자는 유지한다.
|
||||
- 문장형 답변이 아니라 화면 머리글에 맞는 명사형 제목으로 만든다.
|
||||
- 템플릿이 붙이는 고정 부제와 같은 문구를 반복하지 않는다.
|
||||
|
||||
제목 생성이 실패하면 전체 질문을 제목으로 사용하지 않고 짧은 일반 업무 제목으로 안전하게
|
||||
대체한다. 이 규칙은 특정 사용자 코드나 조회 행 수를 조건으로 사용하지 않는다.
|
||||
|
||||
### 현재 선택 사용자와 대화 문맥
|
||||
|
||||
포털의 데모 사용자 선택값은 Bearer token 선택뿐 아니라 질문 해석과 제목 범위의 기준이다.
|
||||
`내`, `나`, `우리` 같은 1인칭 표현은 현재 선택 사용자 ID를 기준으로 독립 질문으로 바꾼다.
|
||||
대화 이력은 같은 `selected_user_id`로 저장된 turn만 불러오며, 제목 생성 모델에도 현재 선택 사용자
|
||||
ID를 별도 입력으로 전달한다. 이전 사용자의 질문에 명시된 팀장·팀 범위가 현재 사용자의 제목으로
|
||||
전파되어서는 안 된다.
|
||||
|
||||
```text
|
||||
현재 사용자 E1001 + "E1001 팀장의 팀원별 ..." → E1001 팀 범위 제목 → VPD 결과 8건
|
||||
현재 사용자 E1002 + "내 담당 선사 ..." → E1002 개인 범위 제목 → VPD 결과 2건
|
||||
```
|
||||
|
||||
제목 문자열이나 예상 행 수를 사용자별로 하드코딩하지 않는다. 사용자 ID, 독립 질문, 실제 선행 조회
|
||||
결과를 모델 입력으로 제공하고 공통 제목 지침으로 생성한다. `report.requestedBy`는 질문에서 추측하지
|
||||
않고 현재 선택 사용자 ID를 사용한다.
|
||||
|
||||
## 포털 표시 계약
|
||||
|
||||
renderer 응답에 유효한 `html` 또는 `rendered_html`이 있으면 HTML artifact가 최종 표현물이다.
|
||||
포털의 일반 답변 생성 지침은 HTML 태그, Markdown 표, 업무 행 전체를 다시 만들지 않고 제목과
|
||||
조회 건수, 아래 리포트 확인 안내만 반환한다. 포털은 같은 조건을 출력 후에도 검사해 모델이
|
||||
HTML을 반환하더라도 안전한 짧은 안내문으로 정규화한다.
|
||||
|
||||
## 조회 질문과 표현 요청 분리
|
||||
|
||||
사용자의 한 문장에는 데이터 요구와 표현 요구가 함께 있을 수 있다. 포털은 Agent instruction으로
|
||||
두 의도를 분리한다.
|
||||
|
||||
```text
|
||||
원문: E1001 팀 선사 KPI를 HTML로 보여줘
|
||||
조회 단계: E1001 팀 선사 KPI를 보여줘
|
||||
표현 단계: 조회된 구조화 행을 HTML 리포트로 렌더링
|
||||
```
|
||||
|
||||
조회 단계 재작성은 직원·팀·기간·지표·필터를 모두 유지하고 `HTML`, `리포트`, `차트`, `대시보드`
|
||||
같은 출력 형식과 생성 행동만 제거한다. 원문은 `report.question`에 보존한다. Select AI가 만든
|
||||
`htmlRow`, HTML 태그 또는 Markdown 표는 구조화 업무 행으로 간주하지 않으며 renderer 입력으로
|
||||
전달하지 않는다.
|
||||
|
||||
서버는 JSON 크기, 행 수, 문자열 길이, 숫자 형식을 제한하고, 템플릿에 주입할 JSON에서
|
||||
`</script>`를 이스케이프한다. payload는 저장하지 않는다.
|
||||
|
||||
## 배포 도구 계약
|
||||
|
||||
`BACKOFFICE_MCP_TOOLS`에 다음과 같이 등록한다. 실제 환경 변수에는 비밀값을 넣지 않는다.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "render_hmm_carrier_report",
|
||||
"label": "HMM 선사 실적 HTML 리포트",
|
||||
"description": "VPD 적용 선사 실적 조회 결과를 HMM HTML 리포트로 표현합니다.",
|
||||
"argumentName": "reportJson",
|
||||
"argumentDescription": "정규화된 선사 실적 리포트 JSON입니다.",
|
||||
"executionType": "AGENT_TOOL",
|
||||
"targetName": "HMM_CARRIER_REPORT_RENDERER",
|
||||
"targetParameterName": "P_REPORT_JSON"
|
||||
}
|
||||
```
|
||||
|
||||
`targetName`은 DBMS_CLOUD_AI_AGENT custom tool `HMM_CARRIER_REPORT_RENDERER`다.
|
||||
|
||||
템플릿에는 `const reportData = __REPORT_DATA__;` 자리만 둔다. DB 함수는 호출 시 전달받은 JSON을
|
||||
이 자리에 삽입하고, 조회 Tool을 호출하거나 기본 업무 행을 보충하지 않는다.
|
||||
56
docs/design/hmm-html-report-mcp/cookbook.md
Normal file
56
docs/design/hmm-html-report-mcp/cookbook.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# 적용·검증 절차
|
||||
|
||||
## 1. 준비
|
||||
|
||||
- `vpd-backoffice` 배포본에 HTML 템플릿과 HMM CI 리소스가 포함되어야 한다.
|
||||
- 조회 도구 `search_carrier_performance`가 기존 `HMM_CARRIER_FEDERATION_SEARCH`를 가리켜야 한다.
|
||||
- 배포 환경의 `BACKOFFICE_MCP_TOOLS`에 `AGENT_TOOL` 도구 계약을 추가한다.
|
||||
|
||||
먼저 `database/adb/83_hmm_carrier_html_report_tool.sql`을 실행한 뒤 다음 명령으로 현재
|
||||
승인 템플릿을 CLOB에 적재한다. 스크립트는 템플릿을 UTF-8 Base64로 복원한다.
|
||||
|
||||
```bash
|
||||
./scripts/load-hmm-carrier-report-template.sh
|
||||
```
|
||||
|
||||
## 2. 확인
|
||||
|
||||
1. 동일 Bearer token으로 `tools/list`를 호출한다.
|
||||
2. `render_hmm_carrier_report`와 입력 속성 `reportJson`이 보이는지 확인한다.
|
||||
3. 먼저 `search_carrier_performance`를 호출한다. 현재 Agent Tool 응답의 실제 행은 `response.result` 안의 JSON 배열 문자열이다.
|
||||
4. 포털이 해당 배열을 행으로 구조화했는지 확인하고 질문·답변 근거·행을 `reportJson`으로 구성해 리포트 도구를 호출한다.
|
||||
5. 응답 `response.html`을 새 탭 또는 sandboxed iframe에서 연다.
|
||||
|
||||
성공 판정은 조회 원본 행 수와 `reportJson.rows` 수가 같고, 제목, 담당자별 막대 차트, 위험 분포,
|
||||
상세 표가 `rows`와 일치하는 것이다.
|
||||
템플릿 내부에 `__REPORT_DATA__`가 남지 않고, 검증 payload의 담당자·선사 식별자가 반환 HTML에
|
||||
포함되는지도 확인한다.
|
||||
|
||||
## 3. 포털 순차 실행 확인
|
||||
|
||||
1. 포털 MCP 설정의 endpoint를 `https://hmm-backoffice.cloud-handson.com/mcp`로 설정하고,
|
||||
허용 목록에 조회 도구와 리포트 렌더링 도구를 모두 넣는다.
|
||||
2. 포털에서 예를 들어 `E1001 팀의 선사 최신 실적을 HMM 리포트로 만들어줘`라고 요청한다.
|
||||
3. 실행 상세에서 첫 단계가 데이터 조회이고 두 번째 단계가 HTML 렌더링인지 확인한다.
|
||||
첫 단계 MCP argument에는 `HTML로 보여줘`, `리포트로 만들어줘` 같은 표현 요청이 없어야 한다.
|
||||
4. 결과 영역에 `생성된 리포트` iframe이 표시되고, 막대·상세 표가 첫 단계 `items`와 일치하는지
|
||||
확인한다.
|
||||
5. 일반 답변에는 `<table>`, `<div>` 또는 Markdown 표가 반복되지 않고, 생성 완료·제목·조회 건수만
|
||||
표시되는지 확인한다.
|
||||
6. 리포트 머리글이 질문 전체 문장이 아니라 출력 형식 문구를 제거한 짧은 업무 제목인지 확인한다.
|
||||
7. `reportJson.rows`의 각 행이 `employeeCode`, `carrierCode`, KPI처럼 업무 필드를 가지며,
|
||||
`htmlRow`나 `<tr>` 문자열을 포함하지 않는지 확인한다.
|
||||
8. 같은 대화에서 사용자를 E1001에서 E1002로 전환한 뒤 `내 담당 선사 ... 리포트로 보여줘`를
|
||||
요청한다. E1002의 독립 질문·제목·`report.requestedBy`에 E1001이 없어야 하며, E1002 권한 범위의
|
||||
행만 표시되어야 한다.
|
||||
|
||||
대표 E1001 팀장 질의의 운영 회귀 기준은 현재 8건이다. 이 숫자는 검증 기준일 뿐 코드나 Tool
|
||||
인수에 고정하지 않는다. 첫 단계 원본에 행이 있는데 `reportJson.rows`가 0건이면 순차 실행 성공이
|
||||
아니며, [문제 해결](troubleshooting.md)의 중첩 응답 항목을 확인한다.
|
||||
|
||||
실패 시 [문제 해결](troubleshooting.md)의 `텍스트만 답하고 리포트가 생성되지 않음`을 따른다.
|
||||
|
||||
## 4. 롤백
|
||||
|
||||
`BACKOFFICE_MCP_TOOLS`에서 리포트 도구 항목을 제거하고 서비스를 재기동하면 기존 조회 MCP에는
|
||||
영향 없이 리포트 후속 호출만 중단된다. 템플릿은 DB나 사용자 데이터에 변경을 만들지 않는다.
|
||||
140
docs/design/hmm-html-report-mcp/troubleshooting.md
Normal file
140
docs/design/hmm-html-report-mcp/troubleshooting.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# 문제 해결
|
||||
|
||||
## 텍스트만 답하고 리포트가 생성되지 않음
|
||||
|
||||
**원인**: 포털이 단일 조회만 실행했거나, MCP discovery 결과에 이전 결과 입력형 렌더러가 없다.
|
||||
|
||||
**확인**:
|
||||
|
||||
1. 포털 설정 endpoint가 `https://hmm-backoffice.cloud-handson.com/mcp`인지 확인한다.
|
||||
2. `tools/list` 결과에 조회 도구와 `reportJson` 입력을 가진 HTML/리포트 렌더러가 모두 있는지 확인한다.
|
||||
3. 포털 실행 상세에서 실행 방식이 `agent`, Agent 단계가 두 번인지 확인한다.
|
||||
|
||||
**해결**: endpoint와 허용 목록을 함께 갱신한 뒤 포털 서비스를 재기동한다. 렌더러 설명에는
|
||||
`조회 결과 후속 처리`처럼 선행 결과를 받는다는 문구를 유지한다.
|
||||
|
||||
**재발 방지**: 새 업무 리포트 도구도 `reportJson`류 입력과 후속 처리 의도를 설명에 선언한다.
|
||||
포털 코드에 특정 도구명을 추가하지 않는다.
|
||||
|
||||
## 렌더러가 입력 형식 오류를 반환함
|
||||
|
||||
**원인**: 조회 도구가 `items`/`results` 배열을 반환하지 않거나, 렌더러가 요구하는 payload 계약과
|
||||
템플릿 계약이 다르다.
|
||||
|
||||
**확인**: 첫 Agent 단계의 응답에 행 배열이 있는지, 두 번째 단계 arguments에 `report`와 `rows`가
|
||||
있는지 확인한다. 비밀값·Bearer token은 실행 상세에 남기지 않는다.
|
||||
|
||||
**해결**: 조회 도구는 구조화 행 배열을 반환하고, 렌더러 함수는 `report`와 `rows` 계약을 유지한다.
|
||||
|
||||
## 생성된 HTML이 화면에 표시되지 않음
|
||||
|
||||
**원인**: 렌더러 응답에 `html` 문자열이 없거나, HTML이 유효하지 않다.
|
||||
|
||||
**확인**: 두 번째 MCP 응답의 `response.html` 존재와 길이를 확인한다.
|
||||
|
||||
**해결**: DB 템플릿 활성 상태와 custom Agent Tool의 반환 형식을 확인한다. 포털은 유효한 `html`
|
||||
또는 `rendered_html`만 sandboxed iframe으로 표시한다.
|
||||
|
||||
## 일반 답변에 HTML 표가 반복되거나 글자가 잘 보이지 않음
|
||||
|
||||
**원인**: 최종 답변 모델이 사용자의 `HTML로 보여줘`를 artifact 생성이 아니라 답변 본문 형식
|
||||
요청으로 해석해 `<table>` 또는 Markdown 표를 다시 작성했다.
|
||||
|
||||
**확인**: MCP 마지막 응답에 유효한 `html`이 있으면서 저장된 `answer`에도 HTML 태그나 표 행이
|
||||
있는지 확인한다.
|
||||
|
||||
**해결**: 최종 답변 지침에 HTML artifact 우선 규칙을 적용하고, 출력 후 검사에서 일반 답변을
|
||||
생성 완료·제목·조회 건수 안내로 정규화한다. iframe CSS나 조회 Tool은 변경하지 않는다.
|
||||
|
||||
**재발 방지**: renderer가 반환된 시나리오에서 일반 답변에 `<table>`과 Markdown 표가 없는지
|
||||
회귀 테스트한다.
|
||||
|
||||
## 리포트 제목에 질문 전체 문장이 표시됨
|
||||
|
||||
**원인**: `report.title`에 사용자 질문을 그대로 복사했다.
|
||||
|
||||
**확인**: renderer 호출의 `reportJson.report.title`과 `question`이 완전히 같은지 확인한다.
|
||||
|
||||
**해결**: 제목 생성 지침으로 출력 형식·행동 문구를 제거한 짧은 명사형 제목을 만들고,
|
||||
`report.question`에는 원문을 유지한다.
|
||||
|
||||
**재발 방지**: 제목과 원문 질문이 역할상 분리되고 제목 길이 제한이 적용되는지 검증한다.
|
||||
|
||||
## 사용자를 바꿨는데 이전 사용자의 이름·팀이 제목에 남음
|
||||
|
||||
**증상**: E1001로 리포트를 만든 뒤 같은 대화에서 E1002를 선택하고 `내 담당 선사`를 요청했는데,
|
||||
데이터는 E1002의 2건이면서 제목은 `E1001 팀장 ...`으로 표시된다.
|
||||
|
||||
**원인**: 질문 독립화 단계가 사용자 구분 없이 이전 대화 turn을 불러와 `내`를 이전 사용자인
|
||||
E1001로 치환했다. VPD는 현재 Bearer token으로 정상 적용되므로 데이터와 제목 범위가 어긋난다.
|
||||
|
||||
**확인**:
|
||||
|
||||
1. 저장된 turn의 `selected_user_id`, `question`, `standalone_question`을 비교한다.
|
||||
2. E1002 turn의 `standalone_question` 또는 renderer `report.title`에 E1001이 남아 있는지 확인한다.
|
||||
3. 선행 조회 행은 E1002 담당 선사만 반환되는지 별도로 확인한다.
|
||||
|
||||
**해결**: 대화 문맥을 현재 `selected_user_id`로 필터링하고, 질문 독립화와 제목 생성에 현재 사용자
|
||||
ID를 명시적으로 전달한다. 1인칭은 현재 사용자만 가리키며 이전 사용자의 관리자·팀 범위를 재사용하지
|
||||
않도록 공통 지침을 적용한다. `report.requestedBy`도 현재 선택 사용자 ID를 사용한다.
|
||||
|
||||
**재발 방지**: 한 대화에서 E1001→E1002로 연속 전환하는 회귀 테스트를 유지한다. 제목과 행 수를
|
||||
사용자별로 고정하지 말고 E1002 결과에 E1001 식별자가 포함되지 않는지를 검사한다.
|
||||
|
||||
## `reportJson.rows`가 `htmlRow`와 `<tr>`만 포함함
|
||||
|
||||
**원인**: 포털이 `HTML로 보여줘`가 포함된 원문을 첫 Select AI 데이터 조회에 그대로 전달해,
|
||||
조회 Tool이 컬럼별 구조화 행 대신 HTML 조각을 반환했다.
|
||||
|
||||
**확인**: 첫 Agent 단계의 MCP argument와 원본 결과를 확인한다. 조회 질문에 표현 형식이 남아 있고
|
||||
행 key가 `htmlRow`뿐이면 이 문제다.
|
||||
|
||||
**해결**: 포털의 데이터 질문 재작성 instruction이 업무 대상·필터·지표는 유지하면서 HTML·리포트·
|
||||
차트 생성 요청만 제거하도록 한다. renderer나 DB 조회 Tool을 변경하지 않는다.
|
||||
|
||||
**재발 방지**: `HTML로 보여줘`가 포함된 통합 질문으로 실제 연속 호출하고, 조회 결과와
|
||||
`reportJson.rows` 모두 업무 필드를 가지며 HTML 태그가 없는지 검증한다.
|
||||
|
||||
## 리포트는 생성됐지만 행이 0건임
|
||||
|
||||
**원인**: 다음 둘 중 하나다.
|
||||
|
||||
1. 선행 조회가 실제로 0건이다.
|
||||
2. 선행 Select AI Tool은 행을 반환했지만 포털이 `response.result` 안의 JSON 배열 문자열을
|
||||
`reportJson.rows`로 구조화하지 못했다.
|
||||
|
||||
**확인**: Agent 첫 단계의 원본 `response.result` 배열 건수와 두 번째 단계 `reportJson.rows`를
|
||||
비교한다. 원본이 8건이고 `rows`가 0건이면 권한이나 Select AI 문제가 아니라 결과 전달 문제다.
|
||||
|
||||
**해결**: 포털의 범용 결과 해석기가 `items`, `results`, `rows`, `response`, `result` wrapper와
|
||||
JSON 배열 문자열을 재귀적으로 처리하는지 확인한다. 조회 Tool, endpoint, VPD 정책, DB package를
|
||||
교체하지 않는다.
|
||||
|
||||
**재발 방지**: 중첩 JSON 배열 회귀 테스트와 운영 연속 호출 검증을 유지한다. 같은 Bearer 문맥에서
|
||||
조회 원본 행 수와 renderer 입력 행 수가 같아야 배포를 완료한다.
|
||||
|
||||
## 첫 리포트는 정상인데 두 번째부터 값이 비거나 깨짐
|
||||
|
||||
**원인**: Select AI가 컬럼 label을 underscore 대신 공백 또는 혼합 대소문자로 반환했고, 포털이
|
||||
underscore만 camelCase로 변환했다.
|
||||
|
||||
**확인**: 연속 호출의 `reportJson.rows`에서 `LATEST_REVENUE_USD`, `LATEST REVENUE USD`,
|
||||
`latest Revenue Usd`가 모두 `latestRevenueUsd`로 정규화되는지 확인한다.
|
||||
|
||||
**해결**: 공백, underscore, hyphen을 공통 단어 경계로 처리한다. 대화 상태나 업무 컬럼 이름을
|
||||
조건문에 하드코딩하지 않는다.
|
||||
|
||||
**재발 방지**: 서로 다른 컬럼 label 표기의 두 응답을 연속 정규화하는 회귀 테스트를 유지한다.
|
||||
|
||||
## 두 번째 리포트의 컬럼이 한글 alias로 바뀌어 깨짐
|
||||
|
||||
**원인**: Select AI가 첫 호출에는 `CARRIER_CODE`, 두 번째 호출에는 `선사코드`처럼 의미는 같지만
|
||||
번역된 alias를 생성했다. 구분자 정규화만으로는 서로 다른 언어의 key를 같은 필드로 판단할 수 없다.
|
||||
|
||||
**확인**: 선행 조회 2건은 정상인데 두 번째 `reportJson.rows`가 `선사명`, `선사코드`,
|
||||
`최신매출Usd` 등을 가지는지 확인한다.
|
||||
|
||||
**해결**: 선사 Select AI query contract에 renderer가 요구하는 ASCII uppercase underscore 출력 alias를
|
||||
선언한다. 실제 SQL, 직원 코드, 결과 값은 고정하지 않는다.
|
||||
|
||||
**재발 방지**: 같은 팀원 질의를 두 번 호출해 두 응답의 key 집합과 renderer HTML을 비교한다.
|
||||
54
docs/runbooks/hmm-mcp-vpd-operations.md
Normal file
54
docs/runbooks/hmm-mcp-vpd-operations.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# HMM MCP·VPD 운영 가이드
|
||||
|
||||
## 1. 적용 범위
|
||||
|
||||
이 문서는 HMM 백오피스와 AI Web Agent Console의 운영 특성만 다룬다. 공통 MCP,
|
||||
VPD, Data Redaction, DDS 설치·검증 원칙은 `main`의 공통 운영 문서를 따른다.
|
||||
|
||||
## 2. HMM 실행 흐름
|
||||
|
||||
```text
|
||||
업무 사용자 로그인
|
||||
→ HttpOnly 인증 cookie 또는 Bearer 검증
|
||||
→ MCP 요청의 업무 사용자 결정
|
||||
→ 팀·담당 선사 권한을 DB context에 설정
|
||||
→ 보호된 HMM View 조회 또는 Select AI 도구 호출
|
||||
→ VPD 행 제한 · Redaction 적용 · FGA 증적 기록
|
||||
→ 선사 KPI·배정·휴가/조직 정보 반환
|
||||
```
|
||||
|
||||
서비스 계정 또는 OCI client-credentials token은 서비스 연결 승인용이다. 업무 사용자
|
||||
권한은 로그인 사용자와 `CB_*` 권한 매핑, 팀·담당 선사 데이터로 결정한다.
|
||||
|
||||
## 3. 운영 데이터와 권한 기준
|
||||
|
||||
| 영역 | 권한 기준 | 확인 대상 |
|
||||
| --- | --- | --- |
|
||||
| 선사 KPI | 사용자의 팀·담당 선사 | VPD predicate, 선사 배정 |
|
||||
| 조직/휴가 | 사용자·팀 소속 | leave/team VPD policy |
|
||||
| MCP 도구 | 광고된 도구와 사용자 인증 | `BACKOFFICE_MCP_TOOLS`, `tools/list` |
|
||||
| 민감 정보 | Redaction 정책과 예외 권한 | 대상 컬럼, policy, 조회 결과 |
|
||||
|
||||
## 4. 일상 점검 순서
|
||||
|
||||
1. 로그인 사용자와 MCP Bearer가 같은 업무 주체로 해석되는지 확인한다.
|
||||
2. `tools/list`의 공개 도구와 실제 호출 가능 도구가 일치하는지 확인한다.
|
||||
3. 서로 다른 팀 또는 담당 선사 사용자가 같은 질문에서 다른 행 집합을 받는지 확인한다.
|
||||
4. 민감 컬럼의 마스킹 결과와 FGA의 `CLIENT_IDENTIFIER`, `RLS_INFO`를 확인한다.
|
||||
5. 권한 변경 뒤 다음 요청에 즉시 반영되는지 확인한다.
|
||||
|
||||
## 5. 장애 대응
|
||||
|
||||
| 증상 | 확인 순서 |
|
||||
| --- | --- |
|
||||
| 로그인했는데 MCP 401/403 | cookie/Bearer, 사용자 매핑, 토큰 만료·회수 |
|
||||
| 선사 데이터가 0건 | 팀·담당 선사 배정, session context, VPD predicate |
|
||||
| 다른 팀 데이터 노출 | 보호 View, VPD policy 적용 객체, 권한 매핑 |
|
||||
| MCP 도구 호출 실패 | 환경변수 도구 목록, 입력 스키마, endpoint 상태 |
|
||||
| 감사 행 없음 | 요청 식별자, FGA policy, Unified Audit Trail |
|
||||
|
||||
## 6. 관련 자료
|
||||
|
||||
- [HMM MCP VPD 런타임 설계](../design/740-hmm-mcp-vpd-runtime/README.md)
|
||||
- [HMM MCP Bearer 설계](../design/712-hmm-backoffice-mcp-bearer/README.md)
|
||||
- [HMM 토큰 설정 런북](hmm-mcp-token-configuration.md)
|
||||
42
scripts/load-hmm-carrier-report-template.sh
Executable file
42
scripts/load-hmm-carrier-report-template.sh
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Load the approved UTF-8 HTML template into Oracle without SQLcl literal mojibake.
|
||||
set -Eeuo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
ENV_FILE="${HMM_REPORT_ENV_FILE:-$ROOT/.env}"
|
||||
TEMPLATE_FILE="${HMM_REPORT_TEMPLATE_FILE:-$ROOT/ai-web-agent-console/assets/hmm-carrier-performance-report.html}"
|
||||
WALLET_DIR="${HMM_REPORT_WALLET_DIR:-/Users/joungminko/devkit/db_conn/Wallet_HMMAIPOC}"
|
||||
[[ -f "$ENV_FILE" ]] && { set -a; . "$ENV_FILE"; set +a; }
|
||||
SQLCL_BIN="${SQLCL_BIN:-$(command -v sql || true)}"
|
||||
DB_USER="${BACKOFFICE_DB_USERNAME:-${ADB_USER:-}}"
|
||||
DB_PASSWORD="${BACKOFFICE_DB_PASSWORD:-${ADB_PASSWORD:-}}"
|
||||
DB_TNS="${ADB_TNS:-}"
|
||||
DB_URL="${BACKOFFICE_DB_URL:-}"
|
||||
if [[ -z "$DB_TNS" && "$DB_URL" =~ ^jdbc:oracle:thin:@([^?]+) ]]; then
|
||||
DB_TNS="${BASH_REMATCH[1]}"
|
||||
fi
|
||||
[[ -x "$SQLCL_BIN" && -f "$TEMPLATE_FILE" && -d "$WALLET_DIR" && -n "$DB_USER" && -n "$DB_PASSWORD" && -n "$DB_TNS" ]] || {
|
||||
echo "SQLCL_BIN, DB credentials, ADB_TNS, and template file are required." >&2; exit 1;
|
||||
}
|
||||
REPORT_B64="$(base64 < "$TEMPLATE_FILE" | tr -d '\n')"
|
||||
[[ ${#REPORT_B64} -le 30000 ]] || { echo "Template is too large for the single-chunk loader." >&2; exit 1; }
|
||||
"$SQLCL_BIN" -thin -tnsadmin "$WALLET_DIR" -s "$DB_USER/$DB_PASSWORD@$DB_TNS" <<SQL
|
||||
WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK
|
||||
DECLARE
|
||||
l_html CLOB := to_clob(utl_i18n.raw_to_char(
|
||||
utl_encode.base64_decode(utl_raw.cast_to_raw('$REPORT_B64')), 'AL32UTF8'));
|
||||
BEGIN
|
||||
MERGE INTO hmm_report_templates dst
|
||||
USING (SELECT 'hmm-carrier-performance' template_key FROM dual) src
|
||||
ON (dst.template_key = src.template_key)
|
||||
WHEN MATCHED THEN UPDATE SET html_template = l_html, template_version = '1.0.0',
|
||||
active_yn = 'Y', updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN INSERT (template_key, template_version, html_template, active_yn)
|
||||
VALUES ('hmm-carrier-performance', '1.0.0', l_html, 'Y');
|
||||
COMMIT;
|
||||
END;
|
||||
/
|
||||
SELECT template_key, template_version, active_yn, dbms_lob.getlength(html_template) html_chars
|
||||
FROM hmm_report_templates WHERE template_key = 'hmm-carrier-performance';
|
||||
EXIT
|
||||
SQL
|
||||
28
vpd-backoffice/config/hmm_carrier_query_contract.json
Normal file
28
vpd-backoffice/config/hmm_carrier_query_contract.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"version": 1,
|
||||
"purpose": "Stable structured output contract for HMM carrier performance reports",
|
||||
"applies_to": "HMM_RDS_FEDERATION_PROFILE carrier assignment and performance questions",
|
||||
"required_objects": [
|
||||
"HMM_CARRIER_ASSIGNMENTS_V",
|
||||
"HMM_RDS_CARRIER_LATEST_V"
|
||||
],
|
||||
"join_contract": "Join HMM_CARRIER_ASSIGNMENTS_V.CARRIER_CODE to HMM_RDS_CARRIER_LATEST_V.CARRIER_CODE.",
|
||||
"required_output_aliases": [
|
||||
"EMPLOYEE_CODE",
|
||||
"EMPLOYEE_NAME",
|
||||
"MANAGER_EMPLOYEE_CODE",
|
||||
"CARRIER_CODE",
|
||||
"CARRIER_NAME",
|
||||
"LATEST_REVENUE_USD",
|
||||
"LATEST_GROSS_MARGIN_USD",
|
||||
"LATEST_SCHEDULE_RELIABILITY_PCT",
|
||||
"LATEST_RISK_LEVEL"
|
||||
],
|
||||
"rules": [
|
||||
"Return one ordinary structured row per employee and assigned carrier.",
|
||||
"Always include every required output alias, even when the natural-language question does not explicitly request the employee columns.",
|
||||
"Use the required ASCII uppercase underscore aliases exactly as written. Never translate aliases, insert spaces in aliases, or return HTML and Markdown.",
|
||||
"For latest or current metrics use HMM_RDS_CARRIER_LATEST_V.",
|
||||
"Do not add, weaken, or emulate authorization predicates. Oracle VPD on HMM_CARRIER_ASSIGNMENTS_V enforces the authenticated employee scope."
|
||||
]
|
||||
}
|
||||
@@ -122,7 +122,7 @@ public class McpSseService {
|
||||
ObjectNode argument = objectMapper.createObjectNode();
|
||||
argument.put("type", "string");
|
||||
argument.put("description", tool.argumentDescription());
|
||||
argument.put("maxLength", 4000);
|
||||
argument.put("maxLength", 64000);
|
||||
properties.set(tool.argumentName(), argument);
|
||||
schema.set("properties", properties);
|
||||
ArrayNode required = objectMapper.createArrayNode();
|
||||
|
||||
@@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import com.cloudhandson.vpdbackoffice.config.BackofficeProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SelectAiServiceTest {
|
||||
@@ -32,4 +34,24 @@ class SelectAiServiceTest {
|
||||
service.validateReadOnlySql("SELECT * FROM x -- bypass"))
|
||||
.isInstanceOf(AppException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void carrierQueryContractRequiresStableAsciiAliases() throws Exception {
|
||||
var contract = new ObjectMapper().readTree(Files.readString(
|
||||
Path.of("config/hmm_carrier_query_contract.json")));
|
||||
|
||||
assertThat(contract.path("required_output_aliases").toString())
|
||||
.contains(
|
||||
"EMPLOYEE_CODE",
|
||||
"CARRIER_CODE",
|
||||
"CARRIER_NAME",
|
||||
"LATEST_REVENUE_USD",
|
||||
"LATEST_GROSS_MARGIN_USD",
|
||||
"LATEST_SCHEDULE_RELIABILITY_PCT",
|
||||
"LATEST_RISK_LEVEL"
|
||||
);
|
||||
assertThat(contract.path("rules").toString())
|
||||
.contains("Never translate aliases")
|
||||
.contains("Oracle VPD");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user