/* Test-only OAuth authorization server and Responses API stand-in, plain
* HTTP on 127.0.0.1, one connection at a time. It plays OpenAI's Sign in
* with ChatGPT (authorize, token, refresh with rotation) and an RFC 8628
* device flow, and answers /v1/responses only for the access token it
* issued last. It exits on its own deadline, so a failed test cannot leave
* it running.
*
* Usage: fake_oauth PORT_FILE DIR DEADLINE_SECONDS SSE_FILE
* GET /api/accounts/authorize 302 to redirect_uri with code, state and an issued client_id
* POST /api/accounts/oauth/token authorization_code (PKCE S256 checked) or refresh_token:
* a refresh token works once; a spent one is refused (counted)
* POST /device/code, /device/token RFC 8628; the third poll is granted
* POST /v1/responses SSE_FILE for the current access token, else 401
* GET /admin/expire the current access token stops working (401) until a refresh
* GET /admin/lifetime?s=N expires_in of tokens issued from now on (default 3600)
* GET /admin/slow?ms=N refreshes wait N ms before answering
* Counters, one line each, in DIR: refreshes, reuse (spent refresh tokens
* offered), exchanges, responses; each request's head and body is appended
* to DIR/requests. Tokens are "acc-N-oauth-sentinel" and "ref-N-oauth-sentinel". */
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
static time_t deadline;
static const char *dir;
static char *sse;
static size_t sse_len;
static int generation, lifetime = 3600, slow_ms, expired, polls;
static char challenge[128], code[64], client_id[64] = "issued-client-7";
static void die(const char *what) {
perror(what);
exit(2);
}
/* ---- SHA-256 (FIPS 180-4), for the PKCE check ---------------------------- */
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
static void sha256(const unsigned char *m, size_t n, unsigned char out[32]) {
uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
size_t total = ((n + 9 + 63) / 64) * 64;
unsigned char *b = calloc(total, 1);
if (!b) {
die("calloc");
}
memcpy(b, m, n);
b[n] = 0x80;
for (int i = 0; i < 8; i++) {
b[total - 1 - i] = (unsigned char)(((uint64_t)n * 8) >> (8 * i));
}
for (size_t off = 0; off < total; off += 64) {
uint32_t w[64], a[8];
for (int i = 0; i < 16; i++) {
w[i] = (uint32_t)b[off + 4 * i] << 24 | (uint32_t)b[off + 4 * i + 1] << 16 | (uint32_t)b[off + 4 * i + 2] << 8 |
b[off + 4 * i + 3];
}
for (int i = 16; i < 64; i++) {
uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
memcpy(a, h, sizeof a);
for (int i = 0; i < 64; i++) {
uint32_t t1 = a[7] + (ROR(a[4], 6) ^ ROR(a[4], 11) ^ ROR(a[4], 25)) + ((a[4] & a[5]) ^ (~a[4] & a[6])) + K[i] + w[i];
uint32_t t2 = (ROR(a[0], 2) ^ ROR(a[0], 13) ^ ROR(a[0], 22)) + ((a[0] & a[1]) ^ (a[0] & a[2]) ^ (a[1] & a[2]));
memmove(a + 1, a, 7 * sizeof a[0]);
a[4] += t1;
a[0] = t1 + t2;
}
for (int i = 0; i < 8; i++) {
h[i] += a[i];
}
}
for (int i = 0; i < 8; i++) {
out[4 * i] = (unsigned char)(h[i] >> 24);
out[4 * i + 1] = (unsigned char)(h[i] >> 16);
out[4 * i + 2] = (unsigned char)(h[i] >> 8);
out[4 * i + 3] = (unsigned char)h[i];
}
free(b);
}
static void b64url(const unsigned char *in, size_t n, char *out) {
static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
size_t o = 0;
for (size_t i = 0; i < n; i += 3) {
unsigned v = (unsigned)in[i] << 16 | (i + 1 < n ? (unsigned)in[i + 1] << 8 : 0) | (i + 2 < n ? in[i + 2] : 0);
out[o++] = a[v >> 18 & 63];
out[o++] = a[v >> 12 & 63];
if (i + 1 < n) {
out[o++] = a[v >> 6 & 63];
}
if (i + 2 < n) {
out[o++] = a[v & 63];
}
}
out[o] = '\0';
}
/* ---- plumbing ----------------------------------------------------------- */
static void bump(const char *name) {
char path[4096], buf[32] = "0";
FILE *f;
long n;
(void)snprintf(path, sizeof path, "%s/%s", dir, name);
if ((f = fopen(path, "r"))) {
if (!fgets(buf, sizeof buf, f)) {
buf[0] = '0';
}
fclose(f);
}
n = strtol(buf, NULL, 10) + 1;
if (!(f = fopen(path, "w"))) {
die(path);
}
fprintf(f, "%ld\n", n);
fclose(f);
}
static void send_all(int fd, const char *p, size_t n) {
while (n > 0) {
ssize_t w = send(fd, p, n, 0);
if (w < 0) {
if (errno == EINTR) {
continue;
}
return;
}
p += w;
n -= (size_t)w;
}
}
static void reply(int fd, int status, const char *type, const char *extra, const char *body) {
char head[1024];
int n = snprintf(head, sizeof head, "HTTP/1.1 %d X\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\n%s\r\n",
status, type, strlen(body), extra ? extra : "");
send_all(fd, head, (size_t)n);
send_all(fd, body, strlen(body));
}
static int hexv(int c) {
return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
}
/* NAME's decoded value in a urlencoded string, into out (empty when absent). */
static void param(const char *q, const char *name, char *out, size_t cap) {
size_t nn = strlen(name), o = 0;
out[0] = '\0';
for (const char *p = q; p && *p;) {
const char *amp = strpbrk(p, "& "), *end = amp ? amp : p + strlen(p);
if (strncmp(p, name, nn) == 0 && p[nn] == '=') {
for (const char *v = p + nn + 1; v < end && o + 1 < cap; v++) {
if (*v == '%' && end - v >= 3 && hexv(v[1]) >= 0 && hexv(v[2]) >= 0) {
out[o++] = (char)(hexv(v[1]) * 16 + hexv(v[2]));
v += 2;
} else {
out[o++] = *v == '+' ? ' ' : *v;
}
}
out[o] = '\0';
return;
}
p = amp && *amp == '&' ? amp + 1 : NULL;
}
}
static void tokens(int fd) {
char body[1024];
generation++;
(void)snprintf(body, sizeof body,
"{\"access_token\":\"acc-%d-oauth-sentinel\",\"refresh_token\":\"ref-%d-oauth-sentinel\",\"expires_in\":%d,"
"\"id_token\":\"h.p.s\",\"token_type\":\"Bearer\",\"scope\":\"openid profile email offline_access "
"resource.invoke chatgpt.tokens.use.direct\"}",
generation, generation, lifetime);
expired = 0;
reply(fd, 200, "application/json", NULL, body);
}
static void handle(int fd) {
static char req[1 << 20];
size_t len = 0, need = 0;
char *body = NULL, method[8], target[8192], v[512], path[4096];
FILE *log;
for (;;) {
struct pollfd p = {fd, POLLIN, 0};
ssize_t r;
if (poll(&p, 1, 5000) <= 0 || (r = recv(fd, req + len, sizeof req - 1 - len, 0)) <= 0) {
break;
}
len += (size_t)r;
req[len] = '\0';
if (!body && (body = strstr(req, "\r\n\r\n"))) {
char *cl = strcasestr(req, "Content-Length:");
body += 4;
need = (size_t)(body - req) + (cl && cl < body ? strtoul(cl + 15, NULL, 10) : 0);
}
if (body && len >= need) {
break;
}
}
if (!body || sscanf(req, "%7s %8191s", method, target) != 2) {
close(fd);
return;
}
(void)snprintf(path, sizeof path, "%s/requests", dir);
if ((log = fopen(path, "a"))) {
fwrite(req, 1, len, log);
fputs("\n----\n", log);
fclose(log);
}
if (strncmp(target, "/api/accounts/authorize?", 24) == 0) {
char redirect[512], state[256], loc[2048];
const char *q = target + 24;
param(q, "client_id", v, sizeof v);
if (strcmp(v, "dynamic_agent_client") != 0) {
reply(fd, 400, "text/plain", NULL, "bad client_id");
goto out;
}
param(q, "code_challenge_method", v, sizeof v);
param(q, "code_challenge", challenge, sizeof challenge);
param(q, "redirect_uri", redirect, sizeof redirect);
param(q, "state", state, sizeof state);
if (strcmp(v, "S256") != 0 || !challenge[0] || strncmp(redirect, "http://127.0.0.1:", 17) != 0 || !state[0]) {
reply(fd, 400, "text/plain", NULL, "bad authorize request");
goto out;
}
param(q, "scope", v, sizeof v);
if (!strstr(v, "chatgpt.tokens.use.direct")) {
reply(fd, 400, "text/plain", NULL, "missing scope");
goto out;
}
(void)snprintf(code, sizeof code, "code-%ld", (long)getpid() ^ (long)time(NULL));
(void)snprintf(loc, sizeof loc, "Location: %s?code=%s&state=%s&client_id=%s\r\n", redirect, code, state, client_id);
reply(fd, 302, "text/plain", loc, "");
} else if (strcmp(method, "POST") == 0 && strcmp(target, "/api/accounts/oauth/token") == 0) {
char grant[64], verifier[256], refresh[256], want[64];
unsigned char d[32];
param(body, "grant_type", grant, sizeof grant);
param(body, "client_id", v, sizeof v);
if (strcmp(v, client_id) != 0) {
reply(fd, 400, "application/json", NULL, "{\"error\":\"invalid_client\"}");
} else if (strcmp(grant, "authorization_code") == 0) {
param(body, "code_verifier", verifier, sizeof verifier);
param(body, "code", v, sizeof v);
sha256((const unsigned char *)verifier, strlen(verifier), d);
b64url(d, sizeof d, want);
if (!code[0] || strcmp(v, code) != 0 || strcmp(want, challenge) != 0) {
reply(fd, 400, "application/json", NULL, "{\"error\":\"invalid_grant\",\"error_description\":\"bad code or verifier\"}");
} else {
code[0] = '\0'; /* a code is spent once */
bump("exchanges");
tokens(fd);
}
} else if (strcmp(grant, "refresh_token") == 0) {
char cur[64];
param(body, "refresh_token", refresh, sizeof refresh);
(void)snprintf(cur, sizeof cur, "ref-%d-oauth-sentinel", generation);
if (slow_ms) {
struct timespec t = {slow_ms / 1000, (long)(slow_ms % 1000) * 1000000L};
nanosleep(&t, NULL);
}
if (generation == 0 || strcmp(refresh, cur) != 0) {
bump("reuse");
reply(fd, 400, "application/json", NULL, "{\"error\":\"invalid_grant\",\"error_description\":\"refresh token already used\"}");
} else {
bump("refreshes");
tokens(fd);
}
} else {
reply(fd, 400, "application/json", NULL, "{\"error\":\"unsupported_grant_type\"}");
}
} else if (strcmp(method, "POST") == 0 && strcmp(target, "/device/code") == 0) {
polls = 0;
reply(fd, 200, "application/json", NULL,
"{\"device_code\":\"dev-1\",\"user_code\":\"WXYZ-1234\",\"verification_uri\":\"http://127.0.0.1/device\","
"\"interval\":1,\"expires_in\":60}");
} else if (strcmp(method, "POST") == 0 && strcmp(target, "/device/token") == 0) {
param(body, "device_code", v, sizeof v);
if (strcmp(v, "dev-1") != 0) {
reply(fd, 400, "application/json", NULL, "{\"error\":\"invalid_grant\"}");
} else if (++polls == 1) {
reply(fd, 400, "application/json", NULL, "{\"error\":\"authorization_pending\"}");
} else if (polls == 2) {
reply(fd, 400, "application/json", NULL, "{\"error\":\"slow_down\",\"interval\":1}");
} else {
tokens(fd);
}
} else if (strcmp(method, "POST") == 0 && strcmp(target, "/v1/responses") == 0) {
char want[96], *auth = strcasestr(req, "\r\nAuthorization: Bearer ");
size_t n = 0;
(void)snprintf(want, sizeof want, "acc-%d-oauth-sentinel", generation);
if (auth) {
auth += 24;
n = strcspn(auth, "\r\n");
}
if (!expired && generation > 0 && auth && n == strlen(want) && strncmp(auth, want, n) == 0) {
char head[256];
int h = snprintf(head, sizeof head, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: %zu\r\n"
"Connection: close\r\n\r\n", sse_len);
bump("responses");
send_all(fd, head, (size_t)h);
send_all(fd, sse, sse_len);
} else {
reply(fd, 401, "application/json", NULL, "{\"error\":{\"message\":\"invalid or expired token\"}}");
}
} else if (strcmp(target, "/admin/expire") == 0) {
expired = 1;
reply(fd, 200, "text/plain", NULL, "ok");
} else if (strncmp(target, "/admin/lifetime?", 16) == 0) {
param(target + 16, "s", v, sizeof v);
lifetime = atoi(v);
reply(fd, 200, "text/plain", NULL, "ok");
} else if (strncmp(target, "/admin/slow?", 12) == 0) {
param(target + 12, "ms", v, sizeof v);
slow_ms = atoi(v);
reply(fd, 200, "text/plain", NULL, "ok");
} else {
reply(fd, 404, "text/plain", NULL, "not found");
}
out:
close(fd);
}
int main(int argc, char **argv) {
struct sockaddr_in a;
socklen_t alen = sizeof a;
int lfd, one = 1;
FILE *f;
if (argc != 5) {
fprintf(stderr, "usage: fake_oauth PORT_FILE DIR DEADLINE_SECONDS SSE_FILE\n");
return 2;
}
signal(SIGPIPE, SIG_IGN);
dir = argv[2];
deadline = time(NULL) + atoi(argv[3]);
if (!(f = fopen(argv[4], "rb")) || fseek(f, 0, SEEK_END) != 0) {
die(argv[4]);
}
sse_len = (size_t)ftell(f);
rewind(f);
if (!(sse = malloc(sse_len + 1)) || fread(sse, 1, sse_len, f) != sse_len) {
die(argv[4]);
}
fclose(f);
lfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
memset(&a, 0, sizeof a);
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(lfd, (struct sockaddr *)&a, sizeof a) != 0 || listen(lfd, 16) != 0 ||
getsockname(lfd, (struct sockaddr *)&a, &alen) != 0) {
die("listen");
}
{
char tmp[4096];
(void)snprintf(tmp, sizeof tmp, "%s.tmp", argv[1]);
if (!(f = fopen(tmp, "w"))) {
die(tmp);
}
fprintf(f, "%d\n", ntohs(a.sin_port));
fclose(f);
rename(tmp, argv[1]);
}
while (time(NULL) < deadline) {
struct pollfd p = {lfd, POLLIN, 0};
if (poll(&p, 1, 200) > 0) {
int fd = accept(lfd, NULL, NULL);
if (fd >= 0) {
handle(fd);
}
}
}
return 0;
}