Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tilfin committed Oct 29, 2023
0 parents commit 95602ff
Show file tree
Hide file tree
Showing 15 changed files with 1,339 additions and 0 deletions.
50 changes: 50 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Logs
logs
*.log
npm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Directory for instrumented libs generated by jscoverage/JSCover
lib
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Dependency directories
node_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Output of 'npm pack'
*.tgz

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# vuepress v2.x temp and cache directory
.temp
.cache

# Stores VSCode versions used for testing VSCode extensions
.vscode-test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Toshimitsu Takahashi (Tilfin Ltd.)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# aesr-config

This is an npm library that facilitates parsing and provides type interfaces for AWS Extend Switch Roles (AESR) configuration text.
It offers both a library and a command-line interface to parse AESR configurations.

## Installation

Install aesr-config by running the following command:

```
$ npm install aesr-config
```

If you wish to use it globally as a command-line tool, install it globally:

```
$ npm install -g aesr-config
```

## Usage

### As a Library

Here’s a more detailed example of how to use aesr-config as a library in your JavaScript code.
This example demonstrates reading a configuration file, parsing it, and logging the output.

```javascript
import { ConfigParser } from 'aesr-config';
import * as fs from 'node:fs';

// Reading configuration text from a file
const configText = fs.readFileSync('config.ini', 'utf8');

// Parsing the configuration text
const profileSet = ConfigParser.parseIni(configText);

// Logging the parsed configuration
console.log(JSON.stringify(profileSet, null, 2));
```

In this example, the configuration text is read from a file named config.ini, and then it is parsed into a JSON object which is then logged to the console.

### Command Line

**aesr-config** is particularly powerful when utilized from the command line, providing a dedicated command **parse-aesr-config** that significantly simplifies the parsing of AESR configurations.
This dedicated command seamlessly integrates into shell scripts and automated workflows.

```
$ parse-aesr-config <<EOF
[profile foo]
aws_account_id = 123456789012
role_name = developer
region = us-east-1
EOF
{"singles":[{"name":"foo","aws_account_id":"123456789012","role_name":"developer","region":"us-east-1"}],"complexes":[]}
```

In this example, the configuration details are passed directly, and the parsed output is displayed in the console as a JSON object.

The `--indent 2` option will format the output JSON with an indentation of 2 spaces, making the JSON output more readable:

```json
{
"singles": [
{
"name": "foo",
"aws_account_id": "123456789012",
"role_name": "developer",
"region": "us-east-1"
}
],
"complexes": []
}
```

## Additional Information

* Ensure that the configuration file or text is correctly formatted according to the AWS Extend Switch Roles specifications.
* The parsed output will contain two sections: singles and complexes, where singles contains individual profiles and complexes contains both base profiles and target profiles, indicating the roles to switch from and to.
36 changes: 36 additions & 0 deletions bin/parse-aesr-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env node
import { argv, stdin, stdout, stderr } from "node:process";
import { ConfigParser } from "../lib/index.js";

let indent = undefined;
for (let i = 2; i < argv.length; i += 2) {
if (argv[i].startsWith("--")) {
const key = argv[i].substring(2);
const val = argv[i + 1];
switch (key) {
case "indent":
indent = Number(val);
break;
default:
throw new Error(`Unknown option: ${key}`);
}
}
}

let data = "";
stdin.on("data", (chunk) => {
data += chunk;
});
stdin.on("end", () => {
try {
const result = ConfigParser.parseIni(data);
stdout.write(JSON.stringify(result, null, indent));
stdout.write("\n");
} catch (err) {
stderr.write(err.constructor.name + ": ");
stderr.write(err.message);
stderr.write("\n");
}
});
stdin.setEncoding("utf8");
stdin.resume();
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "aesr-config",
"version": "0.4.0",
"description": "The utilities for AWS Extend Switch Roles configuration in INI format",
"author": "Toshimitsu Takahashi (Tilfin Ltd.)",
"license": "MIT",
"type": "module",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"bin": {
"parse-aesr-config": "./bin/parse-aesr-config.js"
},
"files": [
"bin",
"lib"
],
"scripts": {
"clean": "rm -r lib/",
"build": "tsc --declaration",
"test": "node --loader tsx --test ./test/*.ts",
"format": "prettier --write \"bin/*.js\" \"src/**/*.ts\" \"test/**/*.ts\""
},
"devDependencies": {
"@types/node": "^20.4.5",
"prettier": "3.0.0",
"tsx": "^3.12.7",
"typescript": "^5.1.6"
},
"engines": {
"node": ">=18"
}
}
123 changes: 123 additions & 0 deletions src/config-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { SectionItem } from "./ini-parser.js";
import { ComplexProfileItem, ProfileItem } from "./type.js";

export class ConfigLoadError extends Error {
public readonly line: number;

constructor(message: string, line: number) {
super(message);
this.line = line;
}
}

export class ConfigLoader {
#singleProfiles: ProfileItem[] = [];
#complexProfiles: ComplexProfileItem[] = [];

load(sectionItems: SectionItem[]): {
singles: ProfileItem[];
complexes: ComplexProfileItem[];
} {
this.#singleProfiles = [];
this.#complexProfiles = [];

const destsBySrcMap: { [key: string]: ProfileItem[] } = {}; // { <srcProfileName>: [<destProfile>... ] }
const singleOrSrcProfiles: ProfileItem[] = [];

sectionItems.forEach((sectionItem) => {
const srcProf = sectionItem.params.source_profile;
delete sectionItem.params.source_profile;

const item = this.createProfileItem(sectionItem);
if (srcProf) {
if (srcProf in destsBySrcMap) {
destsBySrcMap[srcProf].push(item);
} else {
destsBySrcMap[srcProf] = [item];
}
} else {
singleOrSrcProfiles.push(item);
}
});

singleOrSrcProfiles.forEach((item) => {
if (item.name in destsBySrcMap) {
this.#complexProfiles.push({
...item,
targets: destsBySrcMap[item.name],
});
delete destsBySrcMap[item.name];
} else {
this.#singleProfiles.push(item);
}
});

const undefinedSources = Object.keys(destsBySrcMap).join(", ");
if (undefinedSources) {
throw new ConfigLoadError(
`The following profiles are referenced as \`source_profile\` but not defined: ${undefinedSources}`,
0,
);
}

return {
singles: this.#singleProfiles,
complexes: this.#complexProfiles,
};
}

createProfileItem(sectionItem: SectionItem) {
const name = sectionItem.name.replace(/^profile\s+/i, "");
let { aws_account_id, role_arn, role_name, ...others } = sectionItem.params;

if (role_arn) {
if (aws_account_id || role_name) {
throw new ConfigLoadError(
"The profile includes both `role_arn` and either `aws_account_id` or `role_name`.",
sectionItem.startLine,
);
}

const result = this.parseRoleArn(role_arn);
if (!result) {
throw new ConfigLoadError(
"The profile includes invalid `role_arn` parameter.",
sectionItem.startLine,
);
}
aws_account_id = result.aws_account_id;
role_name = result.role_name;
}

if (!aws_account_id)
throw new ConfigLoadError(
"The profile doesn't specify an AWS account ID.",
sectionItem.startLine,
);

return {
name,
aws_account_id,
role_name,
...others,
};
}

parseRoleArn(
roleArn: string,
): { aws_account_id: string; role_name: string } | null {
const [prefix, role] = roleArn.split("/", 2);
if (role === undefined) return null;

const iams = prefix.split(":");
if (
iams[0] !== "arn" ||
iams[2] !== "iam" ||
iams[3] !== "" ||
iams[5] !== "role"
)
return null;

return { aws_account_id: iams[4], role_name: role };
}
}
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ConfigLoader } from "./config-loader.js";
import { IniParser } from "./ini-parser.js";
import { ProfileSet } from "./profile-set.js";

export * from "./config-loader.js";
export * from "./ini-parser.js";
export * from "./profile-set.js";
export type * from "./type.js";

export class ConfigParser {
static parseIni(text: string): ProfileSet {
const sectionItems = new IniParser().parse(text);
const rawProfileSet = new ConfigLoader().load(sectionItems);
return new ProfileSet(rawProfileSet);
}
}
Loading

0 comments on commit 95602ff

Please sign in to comment.