Reorg secrets code

This commit is contained in:
Roberto Alsina 2024-07-02 19:03:29 -03:00
parent 1648f2f99e
commit 2a6f64a53e
2 changed files with 44 additions and 36 deletions

View File

@ -1,44 +1,10 @@
require "kemal" require "kemal"
require "../secrets.cr"
module Secrets module Secrets
SECRETS = Hash(String, String).new extend self
SECRET_PATH = "./secrets/"
# TODO: sanitize all inputs # TODO: sanitize all inputs
# Store secrets in a tree of files
def self.update_secrets
# Save new secrets
SECRETS.map do |_name, value|
funko, name = _name.split("-", 2)
funko_dir = Path.new(SECRET_PATH, funko)
Dir.mkdir_p(funko_dir)
File.write(Path.new(funko_dir, name), value)
end
# Delete secrets not in the hash
Dir.glob(Path.new(SECRET_PATH, "*")).each do |funko_dir|
funko = File.basename(funko_dir)
Dir.glob(Path.new(funko_dir, "*")).each do |secret_file|
name = File.basename(secret_file)
unless SECRETS.has_key?("#{funko}-#{name}")
File.delete(secret_file)
end
end
end
end
# Load secrets from the disk
def self.load_secrets
Dir.glob(Path.new(SECRET_PATH, "*")).each do |funko_dir|
funko = File.basename(funko_dir)
Dir.glob(Path.new(funko_dir, "*")).each do |secret_file|
name = File.basename(secret_file)
value = File.read(secret_file)
SECRETS["#{funko}-#{name}"] = value
end
end
end
# Gets a secret in form {"name": "funko_name-secret_name", "value": "secret_value"} # Gets a secret in form {"name": "funko_name-secret_name", "value": "secret_value"}
post "/secrets/" do |env| post "/secrets/" do |env|
name = env.params.json["name"].as(String) name = env.params.json["name"].as(String)

42
src/secrets.cr Normal file
View File

@ -0,0 +1,42 @@
module Secrets
extend self
SECRETS = Hash(String, String).new
SECRET_PATH = "./secrets/"
# TODO: sanitize all inputs
# Store secrets in a tree of files
def update_secrets
# Save new secrets
SECRETS.map do |_name, value|
funko, name = _name.split("-", 2)
funko_dir = Path.new(SECRET_PATH, funko)
Dir.mkdir_p(funko_dir)
File.write(Path.new(funko_dir, name), value)
end
# Delete secrets not in the hash
Dir.glob(Path.new(SECRET_PATH, "*")).each do |funko_dir|
funko = File.basename(funko_dir)
Dir.glob(Path.new(funko_dir, "*")).each do |secret_file|
name = File.basename(secret_file)
unless SECRETS.has_key?("#{funko}-#{name}")
File.delete(secret_file)
end
end
end
end
# Load secrets from the disk
def load_secrets
Dir.glob(Path.new(SECRET_PATH, "*")).each do |funko_dir|
funko = File.basename(funko_dir)
Dir.glob(Path.new(funko_dir, "*")).each do |secret_file|
name = File.basename(secret_file)
value = File.read(secret_file)
SECRETS["#{funko}-#{name}"] = value
end
end
end
end
Secrets.load_secrets