장 실습: 조건부 요청·세션·CORS를 갖춘 메모 API
상태 코드와 헤더를 고르는 `route`와 바이트를 다루는 `handle`을 연결합니다. 조건부 요청·로그인·CORS의 결과를 여덟 요청으로 확인합니다.
요청 바이트를 받아 응답 바이트를 돌려주는 handle(raw)를 만듭니다. 1편의 메시지 해석, 2편의 상태 코드와 짝 헤더, 3편의 세션 쿠키, 앞 글의 ETag와 CORS 헤더가 모두 들어갑니다.
이 글을 읽고 나면 다음을 할 수 있습니다.
- 상태 코드와 헤더를 고르는
route와 바이트를 다루는handle을 연결합니다. - 조건부 요청·로그인·CORS의 결과를 여덟 요청으로 확인합니다.
시작 상태
Python 3과 9장에서 쓰던 폴더에 mini_http.py를 만듭니다. 9장 1편의 메시지 해석, 2편의 상태 코드, 3편의 세션을 다시 씁니다. 필요한 함수는 아래 완성 파일에 모았습니다. 외부 패키지나 서버를 설치하지 않고 python mini_http.py로 요청 바이트를 직접 넘겨 확인합니다.
완성 조건과 입력
완성 조건은 다음과 같습니다.
OPTIONS요청에는 경로와 상관없이 204와Access-Control-Allow-Methods: GET, POST,Access-Control-Allow-Headers: Content-Type,Access-Control-Max-Age: 600을 돌려줍니다.POST /login은 본문 JSON의user로 세션을 만들고, 204와__Host-sid쿠키를 설정하는Set-Cookie를 돌려줍니다.GET /memos는 200과 메모 목록의 JSON,ETag,Cache-Control: no-cache를 돌려줍니다. 요청의If-None-Match가 지금의ETag와 같으면 본문 없이 304를 돌려줍니다.POST /memos는 유효한 세션 쿠키가 있을 때만 메모를 더하고 201과Location을 돌려줍니다. 없으면 403입니다./memos의 그 밖의 메서드에는 405와Allow: GET, POST를, 다른 경로에는 404를 돌려줍니다.- 모든 응답에
Vary: Origin을 붙이고, 요청의Origin이 허용 목록에 있을 때만Access-Control-Allow-Origin과Access-Control-Allow-Credentials: true를 붙입니다.
힌트: 상태 코드, 헤더, 본문을 고르는 route(method, path, headers, body)와, 바이트를 해석해 route를 부르고 CORS 헤더를 붙여 build_response로 넘기는 handle(raw)로 나눕니다. 메모는 추가만 되므로 ETag는 메모의 개수로 만들 수 있습니다. parse_message가 헤더 이름을 소문자로 바꿔 둔다는 점을 기억합니다.
다음 여덟 줄이 그대로 나오면 완성입니다. 세션 식별자는 실행마다 달라지므로 출력에 넣지 않았습니다.
첫 GET -> HTTP/1.1 200 OK {'etag': '"v1"', 'access-control-allow-origin': 'https://app.example.com'}
조건부 GET -> HTTP/1.1 304 Not Modified {'etag': '"v1"'}
로그인 없이 POST -> HTTP/1.1 403 Forbidden {}
로그인 뒤 POST -> HTTP/1.1 201 Created {'location': '/memos/2'}
추가 뒤 조건부 GET -> HTTP/1.1 200 OK {'etag': '"v2"'}
사전 요청 -> HTTP/1.1 204 No Content {'access-control-allow-methods': 'GET, POST'}
다른 출처의 GET -> HTTP/1.1 200 OK {'vary': 'Origin'}
DELETE -> HTTP/1.1 405 Method Not Allowed {'allow': 'GET, POST'}다를 때 먼저 볼 곳
| 증상 | 먼저 볼 곳 |
|---|---|
| 조건부 GET이 304가 아니라 200이다 | 요청 헤더를 if-none-match처럼 소문자 이름으로 찾았는가. ETag 값에 큰따옴표까지 넣어 비교했는가 |
| 로그인 뒤 POST가 403이다 | Set-Cookie에 쓴 쿠키 이름과 Cookie에서 읽는 이름이 같은가 |
| 사전 요청이 404나 405다 | OPTIONS를 경로와 메서드 검사보다 먼저 처리했는가 |
| 다른 출처의 GET에 허락 헤더가 붙는다 | Origin을 허용 목록과 비교했는가 |
1단계: 메시지와 GET 응답 연결하기
완성 파일의 parse_message, build_message, build_response, request, show로 골격을 만들고 route와 handle을 채웁니다. 먼저 첫 GET과 조건부 GET을 확인합니다. 체크포인트: 첫 응답은 200과 "v1", 같은 검증자를 보낸 응답은 본문 없는 304입니다.
2단계: 로그인 전후의 쓰기 비교하기
POST /login에서 쿠키를 만들고 POST /memos가 그 쿠키를 확인하게 합니다. 체크포인트: 로그인 없이 추가하면 403, 로그인 뒤에는 201과 /memos/2가 나옵니다. 메모가 늘어난 뒤 "v1"로 다시 묻는 GET은 200과 "v2"를 돌려줍니다.
3단계: CORS와 허용 메서드 확인하기
OPTIONS를 먼저 처리하고, handle에서 출처를 검사해 CORS 헤더를 더합니다. 파일 끝의 확인 코드를 모두 실행합니다. 체크포인트: 사전 요청은 204, 다른 출처의 GET에는 vary만, DELETE에는 405와 Allow가 나옵니다.
결과 확인하기
둘째 줄은 ETag가 같아 본문 없이 304를 받았고, content-length를 고르라고 했는데도 나오지 않은 것은 304에 본문 길이를 붙이지 않았기 때문입니다. 셋째 줄은 쿠키가 없어 거절되었습니다. 2편에서 본 것처럼 403은 인증 여부와 상관없이 허락하지 않는다는 뜻으로 쓸 수 있습니다. 401을 쓰려면 WWW-Authenticate로 인증 방식을 알려야 하는데, 쿠키로 하는 로그인에는 그 헤더에 적을 표준 방식이 따로 없어서 이 과제는 403을 골랐습니다. 넷째 줄에서 메모가 둘이 되었으므로, 다섯째 줄에서는 같은 "v1"로 물어도 새 본문과 함께 200이 옵니다. 일곱째 줄의 허용되지 않은 출처에도 서버는 200으로 답했습니다. 허락 헤더가 없어 브라우저가 스크립트에 보여 주지 않을 뿐입니다.
완성 파일 전체
완성 파일 전체 보기
import json
import secrets
from http import HTTPStatus
from http.cookies import SimpleCookie
ALLOWED_ORIGINS = {"https://app.example.com"}
COOKIE_NAME = "__Host-sid"
sessions = {}
memos = ["우유 사기"]
def parse_message(raw):
head, _, rest = raw.partition(b"\r\n\r\n")
start_line, *header_lines = head.decode("ascii").split("\r\n")
headers = {}
for line in header_lines:
name, _, value = line.partition(":")
headers[name.lower()] = value.strip()
length = int(headers.get("content-length", 0))
return start_line, headers, rest[:length]
def build_message(start_line, headers, body=b""):
lines = [start_line] + [f"{name}: {value}" for name, value in headers.items()]
return ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + body
def build_response(status, headers, body):
if status not in (204, 304): # 204와 304는 본문 없이 보낸다
headers["Content-Length"] = str(len(body))
return build_message(f"HTTP/1.1 {status} {HTTPStatus(status).phrase}", headers, body)
def request(method, path, origin, extra=None, body=b""):
headers = {"Host": "api.example.com", "Origin": origin, "Content-Length": str(len(body))}
headers.update(extra or {})
return build_message(f"{method} {path} HTTP/1.1", headers, body)
def show(label, raw, *names): # 시작 줄과 고른 헤더만 출력한다
start_line, headers, body = parse_message(raw)
print(label, "->", start_line, {name: headers[name] for name in names if name in headers})
def route(method, path, headers, body):
if method == "OPTIONS": # 사전 요청에는 허락할 메서드와 헤더만 답한다
return 204, {"Access-Control-Allow-Methods": "GET, POST",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "600"}, b""
if path == "/login" and method == "POST":
sid = secrets.token_urlsafe(32)
sessions[sid] = json.loads(body)["user"]
cookie = f"{COOKIE_NAME}={sid}; Path=/; Max-Age=86400; Secure; HttpOnly; SameSite=Lax"
return 204, {"Set-Cookie": cookie}, b""
if path != "/memos":
return 404, {}, b""
if method == "GET":
etag = f'"v{len(memos)}"' # 메모는 추가만 되므로 개수가 곧 버전이다
found = {"ETag": etag, "Cache-Control": "no-cache"}
if headers.get("if-none-match") == etag:
return 304, found, b""
found["Content-Type"] = "application/json"
return 200, found, json.dumps(memos, ensure_ascii=False).encode("utf-8")
if method == "POST":
cookies = SimpleCookie(headers.get("cookie", ""))
sid = cookies[COOKIE_NAME].value if COOKIE_NAME in cookies else None
if sid not in sessions:
return 403, {}, b""
memos.append(json.loads(body)["text"])
return 201, {"Location": f"/memos/{len(memos)}"}, b""
return 405, {"Allow": "GET, POST"}, b""
def handle(raw):
start_line, headers, body = parse_message(raw)
method, path, version = start_line.split(" ")
status, response_headers, response_body = route(method, path, headers, body)
response_headers["Vary"] = "Origin" # 출처마다 응답 헤더가 다르다
origin = headers.get("origin")
if origin in ALLOWED_ORIGINS:
response_headers["Access-Control-Allow-Origin"] = origin
response_headers["Access-Control-Allow-Credentials"] = "true"
return build_response(status, response_headers, response_body)
APP = "https://app.example.com"
new_memo = json.dumps({"text": "빵 사기"}, ensure_ascii=False).encode("utf-8")
show("첫 GET", handle(request("GET", "/memos", APP)), "etag", "access-control-allow-origin")
show("조건부 GET", handle(request("GET", "/memos", APP, {"If-None-Match": '"v1"'})), "etag", "content-length")
show("로그인 없이 POST", handle(request("POST", "/memos", APP, body=new_memo)))
login = handle(request("POST", "/login", APP, body=b'{"user": "kim"}'))
cookie = parse_message(login)[1]["set-cookie"].split(";")[0]
show("로그인 뒤 POST", handle(request("POST", "/memos", APP, {"Cookie": cookie}, new_memo)), "location")
show("추가 뒤 조건부 GET", handle(request("GET", "/memos", APP, {"If-None-Match": '"v1"'})), "etag")
show("사전 요청", handle(request("OPTIONS", "/memos", APP)), "access-control-allow-methods")
show("다른 출처의 GET", handle(request("GET", "/memos", "https://evil.example.net")), "access-control-allow-origin", "vary")
show("DELETE", handle(request("DELETE", "/memos", APP)), "allow")더 해 보기
- 2편 연습 문제의
/memos/번호조회와 삭제를 더합니다. 삭제가 생기면 개수만으로는 버전을 나타낼 수 없으므로, 바뀔 때마다 1씩 늘리는 버전 번호를 따로 둡니다. - 3편 연습 문제의 로그아웃을
POST /logout으로 더하고, 로그아웃 뒤의 POST가 403이 되는지 확인합니다.
다음 장 암호화의 기초에서는 HTTPS를 이루는 대칭 키와 공개 키 암호, 해시와 전자 서명이 각각 무엇을 지켜 주는지 살펴봅니다.