Skip to content
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
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"extends": ["plugin:github/es6"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"ecmaVersion": 2020,
"sourceType": "module",
"project": "./tsconfig.json"
},
Expand Down
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# remove the v prefix from the tag
tag-version-prefix=""
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ inputs:
default: false

runs:
using: "node12"
using: "node16"
main: "dist/index.js"
256 changes: 135 additions & 121 deletions dist/index.js

Large diffs are not rendered by default.

9,088 changes: 9,081 additions & 7 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "digitalocean-doorkeeper",
"version": "0.3.0",
"version": "0.3.2",
"description": "This Github action allows you to open or close an specific port in your DigitalOcean firewall. It's really useful for deploy in your instances from Github Actions, as they don't provide a list of IPs to add to your security groups.",
"main": "src/main.ts",
"scripts": {
Expand Down Expand Up @@ -44,4 +44,4 @@
"ts-node": "^8.10.2",
"typescript": "^3.9.10"
}
}
}
101 changes: 76 additions & 25 deletions src/digitalocean.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {createApiClient, modules} from "dots-wrapper";
import {IListRequest} from "dots-wrapper/dist/types/list-request";
import { createApiClient, modules } from "dots-wrapper";
import { IListRequest } from "dots-wrapper/dist/types/list-request";

import {ActionConfig} from "./utils";
import { ActionConfig } from "./utils";

import { IFirewallInboundRule, IFirewallOutboundRule } from "dots-wrapper/dist/modules/firewall";
import { config } from "process";

import {IFirewallInboundRule, IFirewallOutboundRule} from "dots-wrapper/dist/modules/firewall";

interface ClientInterface {
firewall: Readonly<{
Expand Down Expand Up @@ -36,53 +38,70 @@ export async function getFirewall({firewall: firewallClient}: ClientInterface, n
throw new Error(`The firewall with name '${name}', doesn't exist.`);
}

// in case the firewall has no inbound rules
firewall.inbound_rules = firewall.inbound_rules || [];

return firewall;
}

function applyRule(config: ActionConfig, rule: IFirewallInboundRule = {protocol: '', ports: '', sources: {}}) {
function applyRule(config: ActionConfig, rule: IFirewallInboundRule = { protocol: '', ports: '', sources: {} }): IFirewallInboundRule | null {
const cloneRule = { ...rule };
const { port, action, protocol, IP } = config;

if (rule.ports != port.toString() || rule.protocol != protocol)
return cloneRule;

if (!cloneRule.protocol) {
cloneRule.protocol = protocol;
}
if (!cloneRule.ports) {
cloneRule.ports = port.toString();
}
if (!cloneRule.sources.addresses) {
cloneRule.sources.addresses = [];
}

const addresses = cloneRule.sources.addresses;
if (action == "add") {
if (!addresses.includes(IP)) {
addresses.push(IP);
}
} else if (action == "remove") {
cloneRule.sources.addresses = addresses.filter(address => address != IP);

}



if(cloneRule.sources?.addresses.length == 0) {
return null;
}

return cloneRule;
}

export function generateInboundRules(oldRules: IFirewallInboundRule[], config: ActionConfig): IFirewallInboundRule[] {
export function generateInboundRules(oldRules: IFirewallInboundRule[] = [], config: ActionConfig): IFirewallInboundRule[] {
const { port, action, protocol } = config;
const existingRules = oldRules.filter(r => r.ports == port.toString() && r.protocol == protocol);

if (!existingRules.length) {
oldRules.push(applyRule(config));
const newRule = applyRule(config);
if (newRule) {
oldRules.push(newRule);
}
return oldRules;
}

return oldRules.map((r, index) => {
return oldRules.reduce((out, r, index) => {
if (action == "remove" || (action == "add" && index == 0)) {
return applyRule(config, r)
const newRule = applyRule(config, r);
if (newRule)
out.push(newRule)
} else {
return r;
out.push(r);
}
});

return out;
}, [] as IFirewallInboundRule[]);
}

export async function updateInboundRules(
{firewall: firewallClient}: ClientInterface,
{ firewall: firewallClient }: ClientInterface,
firewall: modules.firewall.IFirewall,
inboundRules: IFirewallInboundRule[],
dryrun = true
Expand All @@ -95,27 +114,59 @@ export async function updateInboundRules(

const updated = {
...firewall,
inbound_rules: inboundRules,
inbound_rules: inboundRules.length ? inboundRules : [],
outbound_rules: prepareOutboundRules(firewall.outbound_rules)
};

const {
data: {firewall: response}
} = await firewallClient.updateFirewall(updated);
try {

let maxRetries = 10;
const { data: { firewall: response } } = await firewallClient.updateFirewall(updated);
let status = response.status;
const firewallId = (response.id as string);

/*
wait for DO to update the droplets using this firewall
*/
while (true) {

maxRetries--;
if (maxRetries < 0) {
break; // give up
}
console.log(`DO status: ${status}`);
if (status != "waiting") {
break;
}

console.log(" waiting for DO to update the droplets using this firewall...");
await new Promise(resolve => setTimeout(resolve, 2000));

const { data: { firewall: fw } } = await firewallClient.getFirewall({ firewall_id: firewallId });
status = fw?.status || "errored";

}

console.log((response as any).status);
} catch (e) {
console.error("FW Update failed. updated : %j", updated);
console.error("FW Update failed. inboundRules: %j", inboundRules);
console.error(e);
}
}

export function printFirewallRules(inboundRules: IFirewallInboundRule[], title = "") {
export function printFirewallRules(inboundRules: IFirewallInboundRule[] = [], title = "") {
console.log("----------------------");
console.log(`Firewall Inbound Rules ${title}`);
console.log("----------------------");
if(inboundRules.length == 0) {
console.log("** no rules defined **");
}
inboundRules.forEach(rule => {
console.log(`${rule.ports}::${rule.protocol} - ${rule.sources.addresses}`);
console.log(`${rule.ports}::${rule.protocol} - ${rule.sources?.addresses}`);
});
}

function prepareOutboundRules(outboundRules: IFirewallOutboundRule[]): IFirewallOutboundRule[] {
function prepareOutboundRules(outboundRules: IFirewallOutboundRule[] = []): IFirewallOutboundRule[] {
return outboundRules.map(rule => {
const clonedRule = {...rule};
if (clonedRule.ports == "all") {
Expand Down
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ async function main() {
if (config.dryrun) {
console.log("Running in DryRun MODE...");
}
console.log(`Action: '${config.action}' on '${config.protocol}' port '${config.port}' to firewall '${config.firewallName}'`)

const client = getDOClient(config);
const firewall = await getFirewall(client, config.firewallName);
printFirewallRules(firewall.inbound_rules, "(original)");

const newRules = generateInboundRules(firewall.inbound_rules, config);

await updateInboundRules(client, firewall, newRules, config.dryrun);
}

Expand Down
9 changes: 8 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ export async function getConfig(): Promise<ActionConfig> {
const dryrun = core.getInput("dryRun") == "true";

// TODO: try/catch for getting the IP
const IP = await getLocalIP();
let IP;
try {
IP = await getLocalIP();
} catch (error) {
// try again
IP = await getLocalIP();
}

return {
DO_TOKEN: token,
Expand All @@ -56,5 +62,6 @@ export async function getConfig(): Promise<ActionConfig> {
// TODO: remove the export here and test the full configuration
export async function getLocalIP(): Promise<string> {
const response = await fetch("https://ifconfig.me/ip");
if (!response.ok) throw new Error(`Error getting the IP address: ${response.statusText}`);
return response.text();
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"target": "es2019" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"outDir": "./lib" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
Expand Down