aboutsummaryrefslogtreecommitdiff
path: root/src/guff.cr
blob: b610e9608340eba801eb823d56817285e5c72afe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
require "option_parser"
require "http/server"
require "ecr/macros"
require "json"
require "secure_random"
require "./guff/*"

private macro define_model_set_getters(hash)
  {% for name, klass in hash %}
    def {{ name.id }} : {{ klass.id }}
      (@cache[{{ name }}] ||= {{ klass.id }}.new(@context)) as {{ klass.id }}
    end
  {% end %}
end


module Guff
  class Config
    property :mode, :env, :host, :port, :data_dir, :assets_dir

    DEFAULTS = {
      mode:       "help",
      env:        "production",
      host:       "127.0.0.1",
      port:       "8989",
      data_dir:   "./data",
      assets_dir: "/usr/local/share/guff",
    }

    def initialize
      @mode        = DEFAULTS[:mode] as String
      @env         = (ENV["GUFF_ENVIRONMENT"]? || DEFAULTS[:env]) as String
      @host        = (ENV["GUFF_HOST"]? || DEFAULTS[:host]) as String
      @port        = (ENV["GUFF_PORT"]? || DEFAULTS[:port]) as String
      @data_dir    = (ENV["GUFF_DATA_DIR"]? || DEFAULTS[:data_dir]) as String
      @assets_dir  = (ENV["GUFF_ASSETS_DIR"]? || DEFAULTS[:assets_dir]) as String
    end

    VALID_MODES = %w{init run help}

    def mode=(mode : String)
      raise "unknown mode: \"#{mode}\"" unless VALID_MODES.includes?(mode)
      @mode = mode
    end

    VALID_ENVS = %w{development production}

    def env=(env : String)
      raise "unknown environment: \"#{env}\"" unless VALID_ENVS.includes?(env)
      @env = env
    end

    def port=(port : String)
      val = port.to_i
      raise "invalid port: #{port}" unless val > 0 && val < 65535
      @port = port
    end

    def assets_dir=(dir : String)
      raise "missing assets dir: \"#{dir}\"" unless Dir.exists?(dir)
      @assets_dir = dir
    end

    def self.parse(
      app   : String,
      args  : Array(String)
    ) : Config
      r = Config.new

      raise "missing mode" unless args.size > 0

      # get mode
      r.mode = case mode = args.shift
      when "-h", "--help"
        "help"
      else
        mode
      end

      # parse arguments
      p = OptionParser.parse(args) do |p|
        p.banner = "Usage: #{app} [mode] <args>"

        p.separator
        p.separator("Run Options:")

        p.on(
          "-H HOST", "--host HOST",
          "TCP host (defaults to \"#{DEFAULTS[:host]}\")"
        ) do |arg|
          r.host = arg
        end

        p.on(
          "-p PORT", "--port PORT",
          "TCP port (defaults to \"#{DEFAULTS[:port]}\")"
        ) do |arg|
          r.port = arg
        end

        p.separator
        p.separator("Directory Options:")

        p.on(
          "-D DIR", "--data-dir DIR",
          "Data directory (defaults to \"#{DEFAULTS[:data_dir]}\")"
        ) do |arg|
          r.data_dir = arg
        end

        p.on(
          "-A DIR", "--assets-dir DIR",
          "Guff assets directory (defaults to \"#{DEFAULTS[:assets_dir]}\")"
        ) do |arg|
          r.assets_dir = arg
        end

        p.separator
        p.separator("Development Options:")

        p.on(
          "-E ENV", "--environment ENV",
          "Environment (defaults to \"#{DEFAULTS[:env]})\""
        ) do |arg|
          r.env = arg
        end

        p.separator
        p.separator("Other Options:")

        p.on("-h", "--help", "Print usage.") do
          r.mode = "help"
        end
      end

      case r.mode
      when "init"
        # shortcut for -D parameter
        r.data_dir = args.shift if args.size > 0
      when "help"
        # print help
        puts p
      end

      # return config
      r
    end
  end

  module MimeType
    TYPES = {
      ".js":    "text/javascript; charset=utf-8",
      ".css":   "text/css; charset=utf-8",
      ".html":  "text/html; charset=utf-8",
      ".png":   "image/png",
      ".jpeg":  "image/jpeg",
      ".jpg":   "image/jpeg",
      ".otf":   "application/vnd.ms-opentype",
      ".eot":   "application/vnd.ms-fontobject",
      ".svg":   "image/svg+xml",
      ".ttf":   "application/x-font-ttf",
      ".woff":  "application/font-woff",
      ".woff2": "application/font-woff",
    }

    def self.from_path(path : String) : String
      TYPES[File.extname(path)]? || "application/octet-stream"
    end
  end

  module Models
    abstract class Model
      def initialize(@context : Context)
      end
    end

    class UserModel < Model
      def login(user : String, pass : String) : String?
        if @context.development?
          if user == "test" && pass == "test"
            "0"
          else
            nil
          end
        else
          # TODO: handle login
          nil
        end
      end

      def has_role?(user_id : String?, roles : Array(String))
        raise "empty role list" unless roles.size > 0

        if user_id && user_id.size > 0
          if @context.development?
            user_id == "0"
          else
            # TODO: add role query
          end
        else
          # empty user id
          false
        end
      end
    end

    class SessionModel < Model
      def initialize(context : Context)
        super(context)
        @sessions = {} of String => String
      end

      def load(id : String) : String?
        @sessions[id]?
      end

      def save(id : String, data : String)
        if @sessions.has_key?(id)
          @sessions[id] = data
          true
        else
          false
        end
      end

      def delete(id : String?)
        @sessions.delete(id) if id
        false
      end

      def create(data : String) : String
        # generate id
        r = SecureRandom.hex(32)

        # save session
        @sessions[r] = data

        # return session id
        r
      end
    end

    class CSRFModel < Model
      getter :minutes

      def initialize(context : Context)
        super(context)
        @cache = {} of String => Int64

        # expire form after 5 minutes
        # TODO: make this configurable
        @minutes = 5
      end

      def create_token
        remove_expired_tokens
        p @cache

        # generate and cache new token
        r = SecureRandom.hex(16)
        @cache[r] = Time.now.epoch + 60 * @minutes

        # return token
        r
      end

      def use_token(id : String)
        remove_expired_tokens

        if @cache.has_key?(id)
          # remove token, return success
          @cache.delete(id)
          true
        else
          # return failure
          false
        end
      end

      private def remove_expired_tokens
        now = Time.now.epoch

        # remove expired entries
        @cache.delete_if do |key, val|
          val < now
        end
      end
    end
  end

  class ModelSet
    def initialize(@context : Context)
      @cache = {} of Symbol => Models::Model
    end

    define_model_set_getters({
      user:     Models::UserModel,
      session:  Models::SessionModel,
      csrf:     Models::CSRFModel,
    })
  end

  class Session < Hash(String, String)
    getter :session_id

    def initialize(@context : Context)
      super()
      @session_id = nil
    end

    def load(id : String)
      begin
        # clear existing session
        clear

        # load session values
        JSON.parse(@context.models.session.load(id).not_nil!).each do |key, val|
          self[key.as_s] = val.as_s
        end

        # save session id
        @session_id = id

        # return success
        true
      rescue err
        STDERR.puts "session load failed: #{err}"
        # invalid session id, return failure
        false
      end
    end

    def create(hash : Hash(String, String)) : String
      clear
      merge!(hash)
      @session_id = @context.models.session.create(hash.to_json)
    end

    def save
      if valid?
        @context.models.session.save(@session_id, to_json)

        # return success
        true
      else
        # no session, return failure
        false
      end
    end

    def clear
      super
      @session_id = nil
    end

    def delete : String?
      r = @session_id

      if valid?
        @context.models.session.delete(r)
        clear
      end

      r
    end

    def valid?
      @session_id != nil
    end
  end

  class Context
    getter :config

    def initialize(@config : Config)
    end

    def models
      @models ||= ModelSet.new(self)
    end

    def session
      @session ||= Session.new(self)
    end

    def user_id
      session["user_id"]?
    end

    def has_role?(roles : Array(String))
      models.user.has_role?(user_id, roles)
    end

    def development?
      @is_development ||= (@config.env == "development") as Bool
    end
  end

  module Views
    abstract class View
      def initialize(@context : Context)
      end

      def h(s : String) : String
        HTML.escape(s)
      end

      TEMPLATES = {
        script: "<script type='text/javascript' src='%s'></script>",
        style:  "<link rel='stylesheet' type='text/css' href='%s'/>",
      }

      private def assets(key : Symbol, paths : Array(String))
        paths.map { |path| TEMPLATES[key] % [h(path)] }.join
      end
      def scripts(paths : Array(String))
        assets(:script, paths)
      end

      def styles(paths : Array(String))
        assets(:style, paths)
      end
    end

    class AdminPageView < View
      ECR.def_to_s("src/views/admin-page.ecr")
    end

    class LoginPageView < View
      def initialize(context : Context, @error : String? = nil)
        super(context)
      end

      def get_csrf_token
        @context.models.csrf.create_token
      end

      ECR.def_to_s("src/views/login-page.ecr")
    end

    class LogoutPageView < View
      ECR.def_to_s("src/views/logout-page.ecr")
    end
  end

  module Handlers
    abstract class Handler < HTTP::Handler
      def initialize(@context : Context)
        super()
      end
    end

    abstract class AuthenticatedHandler < Handler
      def initialize(context : Context, @roles : Array(String))
        super(context)
      end

      def call(context : HTTP::Server::Context)
        if @context.has_role?(@roles)
          authenticated_call(context)
        else
          call_next(context)
        end
      end

      abstract def authenticated_call(context : HTTP::Server::Context)
    end

    class SessionHandler < Guff::Handlers::Handler
      def call(context : HTTP::Server::Context)
        # check for forged headers
        check_headers(context.request.headers)

        # clear session
        @context.session.clear

        if context.request.cookies.has_key?("guff_sid")
          # load session
          @context.session.load(context.request.cookies["guff_sid"].value)
        end

        call_next(context)
      end

      private def check_headers(headers : HTTP::Headers)
        # FIXME: this isn't needed any more
        %w{x-guff-user-id x-guff-role}.each do |key|
          if headers.has_key?(key)
            raise "forged header: #{key}"
          end
        end
      end
    end

    # TODO: check referrer, add x-frame-options
    class AssetsHandler < Handler
      def initialize(context : Context)
        super(context)
        @etags = {} of String => String
      end

      def call(context : HTTP::Server::Context)
        req_path = context.request.path.not_nil!

        if matching_request?(context.request.method, req_path)
          # get expanded path to file
          if abs_path = expand_path(req_path)
            # get file digest
            etag = get_file_etag(abs_path)

            # check for cache header
            if context.request.headers["if-none-match"]? == etag
              # cached, send 304 not modified
              context.response.status_code = 304
            else
              # not cached, set code and send headers
              context.response.status_code = 200
              context.response.content_type = MimeType.from_path(abs_path)
              context.response.content_length = File.size(abs_path)
              context.response.headers["etag"] = etag

              if context.request.method == "GET"
                # send body for GET requests
                File.open(abs_path) do |fh|
                  IO.copy(fh, context.response)
                end
              end
            end
          else
            # expanded path does not exist
            call_next(context)
          end
        else
          # not a matching request
          call_next(context)
        end
      end

      VALID_METHODS = %w{GET HEAD}
      PATH_RE = %r{^/guff/assets/}

      private def matching_request?(method, path)
        VALID_METHODS.includes?(method) && PATH_RE.match(path)
      end

      private def expand_path(req_path : String) : String?
        # unescape path, check for nil byte
        path = URI.unescape(req_path)
        return nil if path.includes?('\0')

        # build absolute path
        r = File.join(
          @context.config.assets_dir,
          File.expand_path(path.gsub(PATH_RE, ""), "/")
        )

        # return path if file exists, or nil otherwise
        File.file?(r) ? r : nil
      end

      private def get_file_etag(path : String) : String
        # FIXME: rather than a hash this should be an HMAC
        @etags[path] ||= OpenSSL::Digest.new("SHA1").file(path).hexdigest
      end
    end

    # TODO: check referrer, add x-frame-options
    class AdminPageHandler < AuthenticatedHandler
      def initialize(context : Context)
        super(context, %w{admin editor})
      end

      PATH_RE = %r{^/guff/admin.html$}

      def authenticated_call(context : HTTP::Server::Context)
        if context.request.path.not_nil!.match(PATH_RE)
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200
          Views::AdminPageView.new(@context).to_s(context.response)
        else
          call_next(context)
        end
      end
    end

    class LoginPageHandler < Handler
      PATH_RE = %r{^/guff/login.html$}
      VALID_METHODS = %w{GET POST}

      def call(context : HTTP::Server::Context)
        if VALID_METHODS.includes?(context.request.method) &&
           PATH_RE.match(context.request.path.not_nil!)
          case context.request.method
          when "GET"
            reply(context.response)
          when "POST"
            begin
              # create session
              session_id = @context.session.create({
                "user_id": login(context.request.body),
              })

              # add cookie
              context.response.cookies << HTTP::Cookie.new(
                name:       "guff_sid",
                value:      session_id as String,
                http_only:  true,

                # TODO
                # expires:
                # secure:
              )

              # redirect to admin panel
              context.response.headers["location"] = "/guff/admin.html"
              context.response.status_code = 302
            rescue err
              # log error
              STDERR.puts "login failed: #{err}"
              reply(context.response, "invalid login")
            end
          else
            raise "invalid HTTP method"
          end
        else
          call_next(context)
        end
      end

      private def reply(
        response : HTTP::Server::Response,
        error : String? = nil
      )
        response.content_type = "text/html; charset=utf-8"
        response.status_code = 200
        Views::LoginPageView.new(@context, error).to_s(response)
      end

      private def login(body : String?) : String
        # check body
        raise "empty request body" if body.nil? || body.size == 0

        # parse request parameters
        params = HTTP::Params.parse(body.not_nil!)

        # check login parameters
        raise "missing login parameters" unless %w{
          username
          password
          csrf_token
        }.all? do |key|
          params.has_key?(key) && params[key].size > 0
        end

        # check csrf token
        unless @context.models.csrf.use_token(params["csrf_token"])
          raise "invalid csrf token"
        end

        # try login
        user_id =  @context.models.user.login(
          params["username"],
          params["password"]
        )

        # check user id
        raise "invalid credentials" unless user_id

        # return user id
        user_id
      end
    end

    class LogoutPageHandler < Handler
      PATH_RE = %r{^/guff/logout.html$}

      def call(context : HTTP::Server::Context)
        if context.request.method == "GET" &&
           PATH_RE.match(context.request.path.not_nil!)
          # delete session
          @context.session.delete

          # clear cookie
          context.response.cookies << HTTP::Cookie.new(
            name:       "guff_sid",
            value:      "",
            expires:    Time.epoch(0),
            http_only:  true,
          )

          # draw page
          Views::LogoutPageView.new(@context).to_s(context.response)
        else
          call_next(context)
        end
      end
    end

    HANDLERS = [{
      dev:  true,
      id:   :error,
    }, {
      dev:  false,
      id:   :log,
    }, {
      dev:  false,
      id:   :deflate,
    }, {
      dev:  false,
      id:   :session,
    }, {
      dev:  false,
      id:   :assets,
    }, {
      dev:  false,
      id:   :admin,
    }, {
      dev:  false,
      id:   :login,
    }, {
      dev:  false,
      id:   :logout,
    }]

    def self.get(context : Context) : Array(HTTP::Handler)
      HANDLERS.select { |row|
        !(row[:dev] as Bool) || context.development?
      }.map { |row|
        make_handler(row[:id] as Symbol, context)
      }
    end

    def self.make_handler(
      handler_id : Symbol,
      context : Context
    ) : HTTP::Handler
      case handler_id
      when :error
        HTTP::ErrorHandler.new
      when :log
        HTTP::LogHandler.new
      when :deflate
        HTTP::DeflateHandler.new
      when :session
        SessionHandler.new(context)
      when :assets
        AssetsHandler.new(context)
      when :admin
        AdminPageHandler.new(context)
      when :login
        LoginPageHandler.new(context)
      when :logout
        LogoutPageHandler.new(context)
      else
        raise "unknown handler id: #{handler_id}"
      end
    end
  end

  module CLI
    module Actions
      abstract class Action
        def self.run(config : Config)
          new(config).run
        end

        def initialize(@config : Config)
        end

        abstract def run
      end

      class InitAction < Action
        def run
          STDERR.puts "TODO: building directory"
        end
      end

      class RunAction < Action
        def run
          STDERR.puts "TODO: running web server"
          check_dirs

          # create context
          context = Context.new(@config)

          STDERR.puts "listening on %s:%s" % [@config.host, @config.port]

          # run server
          HTTP::Server.new(
            @config.host,
            @config.port.to_i,
            Handlers.get(context)
          ).listen
        end

        private def check_dirs
          {
            "assets": @config.assets_dir,
            "data":   @config.data_dir,
          }.each do |name, dir|
            unless Dir.exists?(dir)
              raise "missing #{name} directory: \"#{dir}\""
            end
          end
        end
      end
    end

    def self.run(app : String, args : Array(String))
      begin
        begin
          config = Config.parse(app, args)
        rescue err
          raise "#{err}.  Use --help for usage"
        end

        case config.mode
        when "init"
          Actions::InitAction.run(config)
        when "run"
          Actions::RunAction.run(config)
        when "help"
          # do nothing
        else
          # never reached
          raise "unknown mode: #{config.mode}"
        end
      rescue err
        STDERR.puts "ERROR: #{err}."
        exit -1
      end
    end
  end
end

Guff::CLI.run($0, ARGV)