Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deploy STA in DEV #63

Merged
merged 7 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .gitleaksignore
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
/src/packages/connectors/connector-saml/README.md:private-key:101
/src/packages/cli/src/commands/database/ogcio/ogcio-seeder.json:generic-api-key:33
/src/packages/cli/src/commands/database/ogcio/ogcio-seeder.json:generic-api-key:42
/src/packages/cli/src/commands/database/ogcio/ogcio-seeder.json:generic-api-key:151
3 changes: 2 additions & 1 deletion .gitpod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ ports:
port: 5432
visibility: public
onOpen: ignore
- port: 5001
# OGCIO - formsie port collision fixed
- port: 7001
onOpen: ignore
- port: 5002
onOpen: ignore
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ EXPOSE 3301
# OGCIO
EXPOSE 3302
# OGCIO
CMD [ "sh", "-c", "export ENCODED_PASSWORD=$(jq --slurp --raw-input --raw-output @uri <(printf \"%s\" $POSTGRES_PASSWORD)) && export DB_URL=\"postgres://$POSTGRES_USER:$ENCODED_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB_NAME\" && export REDIS_URL=\"redis://$REDIS_HOST:$REDIS_PORT\" && npm run cli db seed -- --swe && npm run cli db alteration deploy latest && npm run ogcio:start"]
CMD [ "sh", "-c", "export ENCODED_PASSWORD=$(jq --slurp --raw-input --raw-output @uri <(printf \"%s\" $POSTGRES_PASSWORD)) && export DB_URL=\"postgres://$POSTGRES_USER:$ENCODED_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB_NAME\" && export REDIS_URL=\"redis://$REDIS_HOST:$REDIS_PORT\" && npm run ogcio:start"]
20 changes: 17 additions & 3 deletions README.OGCIO.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ USER_DEFAULT_ORGANIZATION_ROLE_NAMES=OGCIO Employee, OGCIO Manager

3. After the installation, you can start seeding the database. You have to seed in two steps:
- seed Logto's database: `pnpm cli db seed`
- seed custom OGCIO data: `npm run cli db ogcio -- --seeder-filepath="./packages/cli/src/commands/database/ogcio/ogcio-seeder.json"`
- seed custom OGCIO data: `npm run cli db ogcio -- --seeder-filepath="./packages/cli/src/commands/database/ogcio/ogcio-seeder-local.json"`

3.5. Database alteration

Expand Down Expand Up @@ -98,7 +98,7 @@ After installing and seeding the database, you must create a default admin user.

## Custom seeder

We made a custom seeder to ensure the required configuration for OGCIO Building Block integration exists right after the installation. The seeder also makes configuring the deployed Logto instance easy via a CI pipeline. The seeder is located in `packages/cli/src/commands/database/ogcio/`. The configuration for the local dev environment is inside `packages/cli/src/commands/database/ogcio/ogcio-seeder.json`.
We made a custom seeder to ensure the required configuration for OGCIO Building Block integration exists right after the installation. The seeder also makes configuring the deployed Logto instance easy via a CI pipeline. The seeder is located in `packages/cli/src/commands/database/ogcio/`. The configuration for the local dev environment is inside `packages/cli/src/commands/database/ogcio/ogcio-seeder-local.json`.

Each type of configuration has its own dedicated file, which serves as a repository of knowledge about the structure of the configuration and how it should be inserted into the database. This approach ensures a systematic and organized management of the database configuration.

Expand All @@ -112,4 +112,18 @@ This command can take a parameter to specify the input data file, called `seeder

Usage: `npm run cli db ogcio -- --seeder-filepath="DATA_FILE_PATH"`

To seed the default data for local dev environments, run `npm run cli db ogcio -- --seeder-filepath="./packages/cli/src/commands/database/ogcio/ogcio-seeder.json"`.
To seed the default data for local dev environments, run `npm run cli db ogcio -- --seeder-filepath="./packages/cli/src/commands/database/ogcio/ogcio-seeder-local.json"`.

### Limitations

In most cases, we have predefined IDs in our seeder to ensure the same database structure, even if the database was cleared and re-seeded. Logto IDs are simple text fields (no UUID or other validations are applied) with a maximum length of 21 characters. Do not use IDs longer than 21 characters; otherwise, the seeder will fail with a database error!

Be careful when defining a new ID because data duplication is avoided based on this field. If you later want to change the ID of any of your entries, the seeder won't be able to detect the existence of the affected entry, and it will try to create a new one. Creating a duplicate entry with a different ID can cause a database error if some other fields have a unique constraint. If this is not the case, a duplicate entry will be created, which is also a mistake, and we want to avoid any of these situations. Once you have defined an ID, do not change it if unnecessary.

Using resources other than those declared in the seeder's data file is also impossible because referencing any resource outside of the seeder's scope is not supported. The seeder is supposed to create all the required resources and use them to seed the custom configuration into the database.

### Edge cases

Some changes might affect other entries from the database, like the user entities. In this case, a custom migration script is required to resolve the changes necessary to the affected entries. Before any change in the seeder data, analyse the situation to determine if it is safe to perform. The seeder is not intended to resolve conflicts or update other data than the configuration it seeds.

Deletion of existing seeded data via the seeder is not yet possible. Only the permissions (scopes) will be removed and recreated every time the seeder is executed because that is safe and does not cause conflicts with other entries. A custom script or manual action is required for any other data that must be eliminated.
11 changes: 10 additions & 1 deletion azure_pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,13 @@ stages:
parameters:
awsServiceConnection: ${{ variables.awsServiceConnection }}
awsRegion: ${{ variables.awsRegion }}
serviceName: logto
serviceName: logto
- stage: Deploy_Logto_Admin
displayName: Deploy to ECS - logto Admin
dependsOn: Push_Logto
jobs:
- template: pipeline-templates/deploy_ecs.yml
parameters:
awsServiceConnection: ${{ variables.awsServiceConnection }}
awsRegion: ${{ variables.awsRegion }}
serviceName: logto-admin
2 changes: 1 addition & 1 deletion docker-compose-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
[
"sh",
"-c",
"npm run cli db seed -- --swe && npm run cli db alteration deploy latest && npm run cli db ogcio -- --seeder-filepath=\"/etc/logto/packages/cli/src/commands/database/ogcio/ogcio-seeder.json\" && npm start"
"npm run cli db seed -- --swe && npm run cli db alteration deploy latest && npm run cli db ogcio -- --seeder-filepath=\"/etc/logto/packages/cli/src/commands/database/ogcio/ogcio-seeder-local.json\" && npm start"
]
ports:
- 3301:3301
Expand Down
21 changes: 21 additions & 0 deletions mygovid-mock-service/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"rules": {
"no-redeclare": "off",
"no-unused-vars": "off"
},
"env": {
"browser": true,
"node": true
},
"ignorePatterns": ["dist"]
}
2 changes: 2 additions & 0 deletions mygovid-mock-service/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.tap
44 changes: 44 additions & 0 deletions mygovid-mock-service/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "mygovid-mock-service",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "TAP_RCFILE=tap.yml tap",
"start": "node dist/index.js",
"dev": "nodemon | pino-pretty",
"lint": "eslint . --ext .ts",
"build": "echo Build script for the MyGovId mock service not needed so far"
},
"nodemonConfig": {
"ext": "ts,json",
"exec": "node --import tsx src/index.ts"
},
"type": "module",
"author": "",
"license": "ISC",
"dependencies": {
"@fastify/cookie": "^9.3.1",
"@fastify/formbody": "^7.4.0",
"@fastify/sensible": "^5.5.0",
"@fastify/type-provider-typebox": "^4.0.0",
"@sinclair/typebox": "^0.32.16",
"fastify": "^4.26.2",
"fastify-plugin": "^4.5.1",
"jose": "^5.2.4"
},
"devDependencies": {
"@types/node": "^20.11.28",
"@typescript-eslint/eslint-plugin": "^7.5.0",
"@typescript-eslint/parser": "^7.5.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"pino-pretty": "^11.0.0",
"prettier": "^3.2.5",
"tap": "^18.8.0",
"ts-node": "^10.9.2",
"tsx": "^4.7.1",
"typescript": "^5.4.2"
}
}
21 changes: 21 additions & 0 deletions mygovid-mock-service/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import fastify, { FastifyServerOptions } from "fastify";
import routes from "./routes/index.js";
import { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import sensible from "@fastify/sensible";

export async function build(opts?: FastifyServerOptions) {
const app = fastify(opts).withTypeProvider<TypeBoxTypeProvider>();

app.register(import("@fastify/cookie"), {
hook: "onRequest", // set to false to disable cookie autoparsing or set autoparsing on any of the following hooks: 'onRequest', 'preParsing', 'preHandler', 'preValidation'. default: 'onRequest'
parseOptions: {}, // options for parsing cookies
});

app.register(import("@fastify/formbody"));

app.register(routes);

app.register(sensible);

return app;
}
13 changes: 13 additions & 0 deletions mygovid-mock-service/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { build } from "./app.js";

const app = await build();

app.listen({ host: "0.0.0.0", port: 4005 }, (err, address) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log(`MyGovId Mock Service listening at ${address}`);
});

await app.ready();
6 changes: 6 additions & 0 deletions mygovid-mock-service/src/routes/healthcheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { FastifyInstance } from "fastify";
export default async function healthCheck(app: FastifyInstance) {
app.get("/health", async () => {
return { status: "ok" };
});
}
8 changes: 8 additions & 0 deletions mygovid-mock-service/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FastifyInstance } from "fastify";
import healthCheck from "./healthcheck.js";
import logto from "./logto/index.js";

export default async function routes(app: FastifyInstance) {
app.register(healthCheck);
app.register(logto, { prefix: "/logto/mock" });
}
186 changes: 186 additions & 0 deletions mygovid-mock-service/src/routes/logto/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { FastifyInstance } from "fastify";
import fs from "fs";
import path, { dirname } from "path";
import { exportJWK } from "jose";
import { fileURLToPath } from "url";
import { Type } from "@sinclair/typebox";
import {
createMockSignedJwt,
getPublicKey,
streamToString,
} from "./utils/index.js";
import { HttpError } from "../../types/httpErrors.js";

const __dirname = dirname(fileURLToPath(import.meta.url));

export default async function login(app: FastifyInstance) {
app.get<{
Querystring: {
response_type: string;
client_id: string;
redirect_uri: string;
state: string;
nonce: string;
scope: string;
};
}>(
"/auth",
{
schema: {
tags: ["Mock"],
querystring: {
response_type: Type.String(),
client_id: Type.String(),
redirect_uri: Type.String(),
state: Type.String(),
nonce: Type.String(),
scope: Type.String(),
},
response: { 200: Type.String(), 500: HttpError },
},
},
async (request, reply) => {
const { redirect_uri, state } = request.query;

const stream = fs.createReadStream(
path.join(__dirname, "..", "static", "mock-login.html")
);

const result = (await streamToString(stream))
.replace("%REDIRECT_URL%", redirect_uri)
.replace("%STATE%", state);
return reply.type("text/html").send(result);
}
);

app.post<{
Body: {
password: string;
firstName: string;
lastName: string;
email: string;
redirect_url: string;
state: string;
};
}>("/login", async (request, reply) => {
const { password, firstName, lastName, email, redirect_url, state } =
request.body;

if (password !== "123")
reply.redirect(
`/logto/mock/auth?redirect_uri=${redirect_url}&state=${state}`
);

const id_token = await createMockSignedJwt(
{ firstName, lastName, email },
request.headers.origin as unknown as string
);

return reply.redirect(`${redirect_url}?code=${id_token}&state=${state}`);
});

app.post<{
Body: {
code: string;
grant_type: string;
redirect_uri: string;
client_id: string;
client_secret: string;
};
Reply: {
id_token: string;
access_token: string;
token_type: string;
not_before: number;
expires_in: number;
expires_on: number;
id_token_expires_in: number;
profile_info: string;
scope: string;
};
}>(
"/token",
{
schema: {
tags: ["Mock"],
body: Type.Object({
code: Type.String(),
grant_type: Type.String(),
redirect_uri: Type.String(),
client_id: Type.String(),
client_secret: Type.String(),
}),
response: {
200: Type.Object({
id_token: Type.String(),
access_token: Type.String(),
token_type: Type.String(),
not_before: Type.Number(),
expires_in: Type.Number(),
expires_on: Type.Number(),
id_token_expires_in: Type.Number(),
profile_info: Type.String(),
scope: Type.String(),
}),
500: HttpError,
},
},
},
async (request, _) => {
const id_token = request.body.code;
return {
id_token,
access_token: id_token,
token_type: "Bearer",
not_before: Date.now() - 5000,
expires_in: 1800,
expires_on: Date.now() - 5000 + 1800,
id_token_expires_in: 1800,
profile_info:
"eyJ2ZXIiOiIxLjAiLCJ0aWQiOiI4OTc5MmE2ZC0xZWE0LTQxMjYtOTRkZi1hNzFkMjkyZGViYzciLCJzdWIiOm51bGwsIm5hbWUiOm51bGwsInByZWZlcnJlZF91c2VybmFtZSI6bnVsbCwiaWRwIjpudWxsfQ",
scope: "openid",
};
}
);

app.get<{
Reply: {
keys: {
kid: string;
use: string;
kty?: string;
n?: string;
e?: string;
}[];
};
}>(
"/keys",
{
schema: {
tags: ["Mock"],
response: {
200: Type.Object({
keys: Type.Array(
Type.Object({
kid: Type.String(),
use: Type.String(),
kty: Type.Optional(Type.String()),
n: Type.Optional(Type.String()),
e: Type.Optional(Type.String()),
})
),
}),
500: HttpError,
},
},
},
async (request, reply) => {
const publicKey = await getPublicKey();
const { kty, n, e } = await exportJWK(publicKey);

return {
keys: [{ kid: "signingkey.mygovid.v1", use: "sig", kty, n, e }],
};
}
);
}
Loading